[英]Always display at least two decimal places
我想格式化一個數字,使其始終至少有兩個小數位。
樣品:
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
試試這個解決方案(工作),
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}$/, ""));
如果您有更多小數位,則可以輕松更新數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.