【发布时间】:2011-01-14 08:06:00
【问题描述】:
在 JavaScript 中,将数字四舍五入到 N 位小数的典型方法是:
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));
但是,这种方法将舍入到 最大 N 个小数位,而我希望 始终 舍入到 N 个小数位。例如,“2.0”将四舍五入为“2”。
有什么想法吗?
【问题讨论】:
-
通常,你可以使用
toFixed()(developer.mozilla.org/En/Core_JavaScript_1.5_Reference/…),但是在IE中是有问题的:stackoverflow.com/questions/661562/…;您必须编写自己的版本... -
@hoju - 可能更改接受的答案 - David 的答案对于 IE8+ 是正确的,而接受的答案在所有浏览器上都有一些严重的错误。
-
@robocat:你是认真的吗?
标签: javascript math rounding decimal-point