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
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
You could fix to 2 or the count of current places;
var result = num.toFixed(Math.max(2, (num.toString().split('.')[1] || []).length));
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
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.