var ratings = 3193;
var reviews = 9;
var average = parseFloat(ratings) / reviews; //I want a floating point number at the end.
这是正确的方法吗?
var ratings = 3193;
var reviews = 9;
var average = parseFloat(ratings) / reviews; //I want a floating point number at the end.
这是正确的方法吗?
All numbers in JavaScript are double-precision 64-bit binary format IEEE 754. There is no need to typecast "integers" into "floats" as you would expect it from C/C++ and other languages. You need parse*
only if you handle strings.
See also:
primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value
parseInt
, parseFloat
(both take a string as parameter)转换不是必需的。JavaScript 会自动在类型之间进行转换。并且数字实际上并未在内部表示为整数。无论如何,它们都是浮点数。
因此,最简单的解决方案应该具有预期的效果:
var ratings = 3193;
var reviews = 9;
var average = ratings/reviews;
您在示例中所拥有的内容会导致引擎转换ratings
为字符串并将该字符串解析为双精度(理论上会导致它必须以开头的值),然后再将其视为计算中的分子。