我想最多四舍五入小数点后两位,但 _仅限于必要时_。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在 JavaScript 中做到这一点?
原文由 stinkycheeseman 发布,翻译遵循 CC BY-SA 4.0 许可协议
我想最多四舍五入小数点后两位,但 _仅限于必要时_。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在 JavaScript 中做到这一点?
原文由 stinkycheeseman 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果值为文本类型:
parseFloat("123.456").toFixed(2);
如果值为数字:
var numb = 123.23454;
numb = numb.toFixed(2);
有一个缺点,像 1.5 这样的值将给出“1.50”作为输出。 @minitech 建议的修复:
var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.
似乎 Math.round
是更好的解决方案。 但事实并非如此! 在某些情况下,它 不会 正确舍入:
Math.round(1.005 * 100)/100 // Returns 1 instead of expected 1.01!
toFixed() 在某些情况下也 不会 正确舍入(在 Chrome v.55.0.2883.87 中测试)!
例子:
parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.
1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.
我想,这是因为 1.555 在幕后实际上是类似于 float 1.55499994 的东西。
解决方案 1 是使用具有所需舍入算法的脚本,例如:
function roundNumber(num, scale) {
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
}
它也在 Plunker 。
注意: 这不是每个人的通用解决方案。有几种不同的舍入算法。您的实施可能会有所不同,这取决于您的要求。另请参阅 _舍入_。
解决方案2 是避免前端计算并从后端服务器拉取四舍五入的值。
另一种可能的解决方案,也不是防弹的。
Math.round((num + Number.EPSILON) * 100) / 100
在某些情况下,当您将 1.3549999999999998 之类的数字四舍五入时,它会返回不正确的结果。应该是1.35,结果是1.36。
原文由 A Kunin 发布,翻译遵循 CC BY-SA 4.0 许可协议
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读
使用
Math.round()
:或者更具体地说,为了确保 1.005 之类的东西正确舍入,请使用 Number.EPSILON :