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

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

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


当前回答

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>

其他回答

对于现代浏览器,使用toLocaleString:

var num = 1.345;
num.toLocaleString(undefined, { maximumFractionDigits: 2, minimumFractionDigits: 2 });

指定区域设置标记作为控制十进制分隔符的第一个参数。对于点,使用例如English U.S. locale:

num.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

这使:

1.35

大多数欧洲国家使用逗号作为小数分隔符,所以如果你使用瑞典/瑞典地区:

num.toLocaleString("sv-SE", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

它会给:

1, 35

如果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

我是这样解决问题的:

parseFloat(parseFloat(floatString).toFixed(2));