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

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

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


当前回答

这里还有一个泛型函数,可以格式化到任何小数位数:

function numberFormat(val, decimalPlaces) {

    var multiplier = Math.pow(10, decimalPlaces);
    return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}

其他回答

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

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 quantity = 12;

var import1 = 12.55;

var total = quantity * import1;

var answer = parseFloat(total).toFixed(2);

document.write(answer);

function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){ var numbers = string.toString().match(/\d+/g).join([]); numbers = numbers.padStart(decimals+1, "0"); var splitNumbers = numbers.split("").reverse(); var mask = ''; splitNumbers.forEach(function(d,i){ if (i == decimals) { mask = decimal + mask; } if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; } mask = d + mask; }); return pre + mask + pos; } var element = document.getElementById("format"); var money= number_format("10987654321",2,',','.'); element.innerHTML = money; #format{ display:inline-block; padding:10px; border:1px solid #ddd; background:#f5f5f5; } <div id='format'>Test 123456789</div>

用精度方法扩展数学对象

Object.defineProperty(数学、“精度”{ 值:函数(值,精度,类型){ var v = parseFloat(value) p = Math.max(precision,0)||0, T = type||'round'; 返回(数学[t] (v * Math.pow (p)) / Math.pow (p)) .toFixed (p); } }); console.log ( Math.precision(3.1,3), //四舍五入3位 Math.precision(0.12345,2,'ceil'), // ceil 2位数字 Math.precision(1.1) //整数 )

我建议你用

new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(num)

这样,您还将拥有指定国家的本地格式,并且它将确保显示精确的2个小数(无论num是1还是1.12345,它将分别显示1.00和1.12)

在这个例子中,我使用德语本地化,因为我想我的数字显示与千分隔符,所以这将是一些输出:

1 => 1,00
1.12 => 1,12
1.1234 => 1,12
1234 => 1.234,00
1234.1234 => 1.234,12