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

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

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


当前回答

我喜欢:

var num = 12.749;
parseFloat((Math.round(num * 100) / 100).toFixed(2)); // 123.75

小数四舍五入2位, 然后确保用parseFloat()来解析它 返回Number,而不是String,除非你不在乎它是String还是Number。

其他回答

试试下面的代码:

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

var num = new Number(14.12); console.log (num.toPrecision (2));/ /输出14 console.log (num.toPrecision (3));/ /输出14.1 console.log (num.toPrecision (4));/ /输出14.12 console.log (num.toPrecision (5));/ /输出14.120

parseInt(number * 100) / 100;为我工作。

var num1 = “0.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>