17

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
skmasq
  • 4,470
  • 6
  • 42
  • 77

4 Answers4

21

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

 var result = num.toFixed(Math.max(2, (num.toString().split('.')[1] || []).length));
Alex K.
  • 171,639
  • 30
  • 264
  • 288
11

How about using Intl :

Intl.NumberFormat(navigator.language, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 10,
}).format(num)
skube
  • 5,867
  • 9
  • 53
  • 77
0

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

Ringo
  • 3,795
  • 3
  • 22
  • 37
0

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.

Sajad Deyargaroo
  • 1,149
  • 1
  • 7
  • 20
  • This is maximum 4 decimal places, this doesn't solve the issue. – skmasq Dec 09 '13 at 17:43
  • Please see the last line in the answer. You can change this to any number of decimal places eg. `c.toFixed(10).replace(/0{0,8}$/, "")` First number is the max decimal places that we can have (10 in this case) and second number is max-min (8 in this case). – Sajad Deyargaroo Dec 09 '13 at 17:59
  • 2
    Alex K. answer is better because it doesn't set maximum decimal places. – skmasq Dec 09 '13 at 19:07