Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to have 2 symbols after dot [duplicate]

Tags:

javascript

php

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?

like image 288
pzztzz Avatar asked Nov 22 '11 13:11

pzztzz


2 Answers

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.

like image 190
Russell Dias Avatar answered Oct 05 '22 23:10

Russell Dias


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';
like image 43
Linus Kleen Avatar answered Oct 05 '22 23:10

Linus Kleen