skmasq
skmasq

Reputation: 4511

Always display at least two decimal places

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

Upvotes: 20

Views: 8081

Answers (4)

skube
skube

Reputation: 6175

How about using Intl :

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

Upvotes: 13

Sajad Deyargaroo
Sajad Deyargaroo

Reputation: 1149

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.

Upvotes: 1

Ringo
Ringo

Reputation: 3965

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

Upvotes: 0

Alex K.
Alex K.

Reputation: 175768

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

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

Upvotes: 22

Related Questions