我希望格式化一个数字,使其始终至少有两位小数。
示例:
1
2.1
123.456
234.45
输出:
1.00
2.10
123.456
234.45
我希望格式化一个数字,使其始终至少有两位小数。
示例:
1
2.1
123.456
234.45
输出:
1.00
2.10
123.456
234.45
您可以将其修复为2或当前场所的计数。
var result = num.toFixed(Math.max(2, (num.toString().split('.')[1] || []).length));
试试使用 Intl:
Intl.NumberFormat(navigator.language, {
minimumFractionDigits: 2,
maximumFractionDigits: 10,
}).format(num)
试试这个:
var num = 1.2;
function decimalPlaces(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
if(decimalPlaces(num) < 2){
num = num.toFixed(2);
}
alert(num);
这里是 jsfiddle
1.23
,我想要 1.2345
。 - skmasq尝试这个解决方案(可行),
var a= 1,
b= 2.1,
c = 123.456,
d = 234.45;
console.log(a.toFixed(4).replace(/0{0,2}$/, ""));
console.log(b.toFixed(4).replace(/0{0,2}$/, ""));
console.log(c.toFixed(4).replace(/0{0,2}$/, ""));
console.log(d.toFixed(4).replace(/0{0,2}$/, ""));
c.toFixed(10).replace(/0{0,8}$/, "")
第一个数字是我们可以拥有的最大小数位数(在本例中为10),第二个数字是最大-最小值(在本例中为8)。 - Sajad Deyargaroo