如何在Javascript中四舍五入小数点后两位

How do you round a two decimal places in Javascript?

本文关键字:两位 小数点 Javascript 四舍五入      更新时间:2023-09-26

我正试图将一个数字四舍五入到2个小数,它给了我整数!

var 4 = 10.99 + 89.78899999
total = number(a) + number(b);

这是我目前拥有的:

Math.round(total, 2);  // this gives me 101 I need it to show 100.78

这样做的诀窍是什么?

您应该像使用一样使用toFixed(2)

alert(12.432432.toFixed(2)); // 12.43

Math.round表示:"返回四舍五入到最接近整数的数值。"

顺便说一句,4在javascript中不是一个有效的变量名,它不能以数字开头。

哪些字符对JavaScript变量名有效?