Im using javascript round
to round the numbers. But when the value is $106.70
the output shows only $106.7
and its missing the last 0
. How can I add a zero for numbers ending with a zero or is there any easier way than using if else to check this?
Im using javascript round
to round the numbers. But when the value is $106.70
the output shows only $106.7
and its missing the last 0
. How can I add a zero for numbers ending with a zero or is there any easier way than using if else to check this?
1 Answer
Reset to default 9You can use the .toFixed
method:
var n = 106.72; console.log(n.toFixed(2)); //=> '106.72'
var n = 106.70; console.log(n.toFixed(2)); //=> '106.70'
var n = 106.7; console.log(n.toFixed(2)); //=> '106.70'
var n = 106; console.log(n.toFixed(2)); //=> '106.00'
And it rounds:
var n = 106.76; console.log(n.toFixed(1)); //=> '106.8'