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

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

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


当前回答

如果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中的四舍五入小数

其他回答

(num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")
function currencyFormat (num) {
    return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
}

console.info(currencyFormat(2665));   // $2,665.00
console.info(currencyFormat(102665)); // $102,665.00

试试下面的代码:

function numberWithCommas(number) { 

   var newval = parseFloat(Math.round(number * 100) / 100).toFixed(2);

   return newval.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

你没有告诉我们全部情况。

alert(parseFloat(1). tofixed(2))显示1.00在我的浏览器,当我粘贴到位置栏。 然而,如果你事后对它做了一些事情,它就会恢复。

alert(parseFloat(1).toFixed(2)) 变量数 = 2 document.getElementById('spanId').innerHTML = (parseFloat(num).toFixed(2) - 1) <span id=“spanId”></span>

shows 1 and not 1.00
(Math.round(num * 100) / 100).toFixed(2);

现场演示

var num1 = “1”; document.getElementById('num1').innerHTML =(Math.round(num1 * 100) / 100).toFixed(2); var num2 = “1.341”; document.getElementById('num2').innerHTML =(Math.round(num2 * 100) / 100).toFixed(2); var num3 = “1.345”; document.getElementById('num3').innerHTML =(Math.round(num3 * 100) / 100).toFixed(2); 跨度 { 边框:1px 实心 #000; 边距:5px; 填充:5px; } <span id=“num1”></span> <span id=“num2”></span> <span id=“num3”></span>

注意,它将四舍五入到小数点后2位,因此输入1.346将返回1.35。