问题描述
我有一个浮点数,例如137.57667565656,但我想四舍五入,使得小数点后只有两个尾随数字,例如新的浮点数将是137.58.
I have a float number like 137.57667565656 but I would like to round it such that there are only two trailing digits after the decimal point like the new float number will be 137.58.
到目前为止,我已经尝试过:
I tried this so far:
(Math.round((value*100)/100)).toFixed(2).toString();
但不幸的是,它将我的值四舍五入为137.00.它将小数位添加为零,为什么呢?
But unfortunately, it rounds my value to 137.00. It adds the decimals places as zeroes, why?
如何实现以上目标?
推荐答案
您期望什么?
(value*100)/100
仅返回 value 的原始值,因此
Math.round((value*100)/100))
等同于:
Math.round(value)
您将拥有:
Math.round(value).toFixed(2).toString();
因此 value 会四舍五入为整数, toFixed 将添加两个小数位并返回一个字符串,因此 toString 部分是多余的.如果您希望将 value 舍入到小数点后四位,则:
so value is rounded to an integer, toFixed will add two decimal places and return a string so the toString part is redundant. If you wish to round value to four decimal places, then:
value.toFixed(4)
将完成这项工作:
var x = 137.57667565656;
console.log(x.toFixed(4)); // 137.5767
如果要将其四舍五入,但将其显示为4,则:
If you want to round it to 2 places but present it as 4, then:
Number(x.toFixed(2)).toFixed(4) // 137.5800
这篇关于如何舍入浮点数,使小数点后只有两位尾随数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!