javascript - Javascript 中的舍入问题

标签 javascript

我在百分比计算和结果四舍五入方面遇到以下问题。

如果我使用 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() 函数来舍入数字。

引用:

Math.Round()

关于javascript - Javascript 中的舍入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28064266/

相关文章:

javascript - Redux 中间件无限循环?

javascript - 如何在javascript中找到最近的最高千位

Javascript history api - window.history.forward() 可用性

javascript - 在nodejs中运行cron作业

javascript - 比较 Javascript 数组中的数字以获得最大的数字

javascript - 滚动时更改背景附件会导致 WebKit 中的图形故障

php - Drupal 错误地转义了 javascript 中的标签

javascript - angular.element ('#home' )返回未定义

html - 如何替换 "li"中的文本

javascript - 使用 knockout.js 更新所选内容中的 div