Possible Duplicate:
How can I format numbers as money in JavaScript?
Format number to always show 2 decimal places
How do I round to 2 decimal places?
In PHP I can do the following to round to 2 decimal places;
$number = 3.45667;
$result = number_format($number, 2, '.', ''); // 3.46
How can I do the same in JavaScript?
var number = 3.45667;
number.toFixed(2)
// returns "3.46"
toFixed()
is the number of digits to appear after the decimal point. It will also pad on 0's to fit the input size.
var number = 3.45667;
number = Math.round(100 * number) / 100;
This will however not quite work like PHP's number_format()
. I.e. it will not convert 2.4 to 2.40. In order for that to work, you'll need a little more:
number = number.toString();
if (!number.match(/\./))
number += '.';
while (!number.match(/\.\d\d$/))
number += '0';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With