我在百分比计算和结果四舍五入方面遇到以下问题。
如果我使用 Math.ceil
:
var total = 66666;
var test1 = Math.ceil(60 / 100 * total);
var test2 = Math.ceil(23.5 / 100 * total);
var test3 = Math.ceil(14 / 100 * total);
var test4 = Math.ceil(2.5 / 100 * total);
然后 test1 + test2 + test3 + test4 = 66664
如果我使用 ParseInt
:
var total = 66666;
var test1 = parseInt(60 / 100 * total);
var test2 = parseInt(23.5 / 100 * total);
var test3 = parseInt(14 / 100 * total);
var test4 = parseInt(2.5 / 100 * total);
然后 test1 + test2 + test3 + test4 = 66668
我尝试将我的脚本从 Python 重写为 Javascript,在 Python 中我没有遇到任何这样的问题。
最佳答案
如果您阅读 doc parseInt
是如何工作的 你发布问题所在:
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
Syntax
parseInt(string, radix);
string
The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored.
radix
An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
Description
The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN.
例子:
parseInt(2.1) // returns 2
parseInt(2.9) // returns 2 too
parseInt('2.99') // returns 2
还建议在调用 parseInt
时也将基数作为参数传递。
在 javascript 中最好使用 Math.round()
函数来舍入数字。
引用:
关于javascript - Javascript 中的舍入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28064266/