我不知道如何做到这一点?我正在添加逗号数字,结果当然总是一个有太多逗号后面数字的数字。有人可以帮忙吗?
我不知道如何做到这一点?我正在添加逗号数字,结果当然总是一个有太多逗号后面数字的数字。有人可以帮忙吗?
编辑2:
使用Number
对象的toFixed
方法,如下所示:
var num = Number(0.005) // The Number() only visualizes the type and is not needed
var roundedString = num.toFixed(2);
var rounded = Number(roundedString); // toFixed() returns a string (often suitable for printing already)
将42.0054321四舍五入为42.01
将0.005四舍五入为0.01
将-0.005四舍五入为-0.01(所以绝对值在.5边界处进位)
3.1415
变成了 3.00
。 - user1180790更新:请记住,当本答案最初于2010年编写时,下列的 toFixed()
函数工作方式略有不同。现在,toFixed()
似乎会进行一些四舍五入,但不是以严格的数学方式进行。因此要小心使用,自己进行测试... 下面描述的方法将按照数学家的预期进行四舍五入。
toFixed()
方法将数字转换为字符串,并保留指定数量的小数位。它实际上并不会对数字进行四舍五入,而是截断数字。Math.round(n)
会将一个数四舍五入到最近的整数。因此将:0.5 -> 1; 0.05 -> 0
所以如果你想将数字 0.55555 四舍五入到小数点后第二位,可以按照以下步骤操作(这是逐步的概念):
0.55555 * 100
= 55.555 Math.Round(55.555)
-> 56.00056.000 / 100
= 0.56000 (0.56000).toFixed(2)
-> 0.56代码如下:
(Math.round(number * 100)/100).toFixed(2);
(Math.round(123.12124 * 100)/100).toFixed(4); ===> 123.1200- Maksim Nesterenko
.toFixed()
实际上是将数字四舍五入。我刚测试了一下:0.6666.toFixed(3)
=> 0.667 - Victor Gorban这对我起作用:
var new_number = float.toFixed(2);
示例:
var my_float = 0.6666
my_float.toFixed(3) # => 0.667
0.6666.toFixed(3)
变成了0.666
而不是0.667
。@Andrei似乎有正确的解决方案来正确地进行四舍五入。 - Joshua PintertoFixed()
完美地工作了:0.6666.toFixed(3) # => 0.667
。我会把它加入到你的答案中。 - Joshua Pinter之前的回答忘记将输出再次输入为数字。有几种方法可以做到这一点,具体取决于您的喜好。
Previous answers忘了将输出转换为数字。有几种方法可以做到这一点,具体取决于您的个人喜好。
+my_float.toFixed(2)
Number(my_float.toFixed(2))
parseFloat(my_float.toFixed(2))
Math.round(number*100)/100
虽然我们在这里有许多答案并提供了很多有用的建议,但每一个答案仍然缺失一些步骤。
因此,这里有一个完整的解决方案封装成小函数:
function roundToTwoDigitsAfterComma(floatNumber) {
return parseFloat((Math.round(floatNumber * 100) / 100).toFixed(2));
}
如果您有兴趣了解这是如何工作的:
toFixed(2)
保留2位小数并丢弃其他无用部分parseFloat()
函数将其转换回浮点数,因为toFixed(2)
返回字符串注意:如果由于涉及货币价值而保留最后2位小数,并且进行财务计算,请记住这不是一个好主意,最好使用整数值代替。
alert(+(Math.round(number + "e+2") + "e-2"));
console.log((Math.random().toFixed(2)));
我已经习惯使用 tofixed(),仍然工作正常。
Math.sign(num) * (Math.round((Math.abs(num) + Number.EPSILON) * 1e2) / 1e2);
function round(value, precision) {
if(precision == 0)
return Math.round(value);
exp = 1;
for(i=0;i<precision;i++)
exp *= 10;
return Math.round(value*exp)/exp;
}