我想格式化我的数字,总是显示2小数点后,四舍五入适用的地方。

例子:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35

我一直在用这个:

parseFloat(num).toFixed(2);

但是它把1显示为1,而不是1.00。


当前回答

刚刚遇到了这个最长的线程,下面是我的解决方案:

parseFloat(Math.round((parseFloat(num * 100)).toFixed(2)) / 100 ).toFixed(2)

如果有人能找到漏洞就告诉我

其他回答

如果value = 1.005,此回答将失败。

作为一个更好的解决方案,可以使用指数表示的数字来避免舍入问题:

Number(Math.round(1.005+'e2')+'e-2'); // 1.01

@Kon和原作者建议的更简洁的代码:

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)

你可以在末尾加上toFixed()以保留小数点,例如:1.00,但注意它将返回字符串。

Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)

来源:JavaScript中的四舍五入小数

你在找地板吗?

变量数 = 1.42482; var num2 = 1; var fnum = Math.floor(num).toFixed(2); var fnum2 = Math.floor(num2).toFixed(2); console.log(fnum + “ 和 ” + fnum2);两个值均为 1.00

一个更通用的N位舍入解决方案

function roundN(num,n){
  return parseFloat(Math.round(num * Math.pow(10, n)) /Math.pow(10,n)).toFixed(n);
}


console.log(roundN(1,2))
console.log(roundN(1.34,2))
console.log(roundN(1.35,2))
console.log(roundN(1.344,2))
console.log(roundN(1.345,2))
console.log(roundN(1.344,3))
console.log(roundN(1.345,3))
console.log(roundN(1.3444,3))
console.log(roundN(1.3455,3))

Output

1.00
1.34
1.35
1.34
1.35
1.344
1.345
1.344
1.346
Number(1).toFixed(2);         // 1.00
Number(1.341).toFixed(2);     // 1.34
Number(1.345).toFixed(2);     // 1.34 NOTE: See andy's comment below.
Number(1.3450001).toFixed(2); // 1.35

. getelementbyid(“line1”)。innerHTML = Number(1).toFixed(2); . getelementbyid(么)。innerHTML = Number(1.341).toFixed(2); . getelementbyid(“line3”)。innerHTML = Number(1.345).toFixed(2); . getelementbyid(“line4”)。innerHTML = Number(1.3450001).toFixed(2); < span id = " line1 " > < / span > < br / > < span id = "么" > < / span > < br / > < span id = " line3 " > < / span > < br / > < span id = " line4 " > < / span >

这是用的安全解。这将修复。15的舍入

function myFunction(a) {

    return Math.round((a + Number.EPSILON) * 100) / 100
}