我想格式化我的数字,总是显示2小数点后,四舍五入适用的地方。
例子:
number display
------ -------
1 1.00
1.341 1.34
1.345 1.35
我一直在用这个:
parseFloat(num).toFixed(2);
但是它把1显示为1,而不是1.00。
我想格式化我的数字,总是显示2小数点后,四舍五入适用的地方。
例子:
number display
------ -------
1 1.00
1.341 1.34
1.345 1.35
我一直在用这个:
parseFloat(num).toFixed(2);
但是它把1显示为1,而不是1.00。
当前回答
这里有另一个只使用底价的四舍五入的解决方案,这意味着,确保计算的金额不会大于原始金额(有时交易需要):
Math.floor(num* 100 )/100;
其他回答
好消息! ! 似乎javascript的新版本ES2020(我只是使用)提供了这个函数的新行为。
let ff:number =3
console.info(ff.toFixed(2)) //3.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
对于现代浏览器,使用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
function formatValeurDecimal(valeurAFormate,longueurPartieEntier,longueurPartieDecimal){
valeurAFormate = valeurAFormate.replace(",",".")
valeurAFormate = parseFloat(valeurAFormate).toFixed(longueurPartieDecimal)
if(valeurAFormate == 'NaN'){
return 0
}
//____________________valeurPartieEntier__________________________________
var valeurPartieEntier = valeurAFormate | 0
var strValeur = valeurPartieEntier.toString()
strValeur = strValeur.substring(0, longueurPartieEntier)
valeurPartieEntier = strValeur
//____________________valeurPartieDecimal__________________________________
strValeur = valeurAFormate
strValeur = strValeur.substring(strValeur.indexOf('.')+1)
var valeurPartieDecimal = strValeur
valeurAFormate = valeurPartieEntier +'.'+valeurPartieDecimal
if(valeurAFormate == null){
valeurAFormate = 0
}
return valeurAFormate
}
用精度方法扩展数学对象
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) //整数 )