Always display at least two decimal places

时光怂恿深爱的人放手 提交于 2019-12-10 02:14:09

问题


I want to format a number so that it always have at least two decimal places.

Samples:

1
2.1
123.456
234.45

Output:

1.00
2.10
123.456
234.45

回答1:


You could fix to 2 or the count of current places;

 var result = num.toFixed(Math.max(2, (num.toString().split('.')[1] || []).length));



回答2:


How about using Intl :

Intl.NumberFormat(navigator.language, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 10,
}).format(num)



回答3:


Try this:

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);

Here is jsfiddle




回答4:


Try this solution (working),

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}$/, ""));

If you have more decimal places, you can updated the number easily.



来源:https://stackoverflow.com/questions/20473940/always-display-at-least-two-decimal-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!