6

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?

Community
  • 1
  • 1
pzztzz
  • 181
  • 3
  • 8

4 Answers4

7
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.

Russell Dias
  • 70,980
  • 5
  • 54
  • 71
6
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';
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
1

You can use the below code

var number = 3.45667;
number.toFixed(2);

If you want to use rounding you'd multiply by 100 first, then round and divide by 100.

Munter
  • 1,079
  • 5
  • 7
0

the simple version: use .toFixed() like this:

var num= 3.45667;
num.toFixed(2); // 3.46

the complicated version, if you want the exact behaviour of number_format() is using this method from php.js:

var num= 3.45667;
number_format($number, 2, '.', ''); // 3.46
oezi
  • 51,017
  • 10
  • 98
  • 115