tags:

views:

6509

answers:

4

How can i get just 2 digits after comma in javascript? For example, 0.34 instead of 0.3445434.

+5  A: 
var result = Math.round(original*100)/100;

The specifics, in case the code isn't self-explanatory.

edit: ...or just use toFixed, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)

kkyy
In which case he should use Math.floor(). For positive numbers, that is...
xtofl
Why would it give 0.35? 0.3445434 * 100 = 34.45434, Math.round(34.45434) = 34, 34 / 100 = 0.34...?
kkyy
+2  A: 
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding
Ilya Birman
+19  A: 

There are functions to round numbers. For example:

var x = 5.0364342423;
print(x.toFixed(2));

will print 5.04.

Tim Büthe
I would recommend against using print() in a browser though
cobbal
right, good point, but nobody said this would run in a browser :)
Tim Büthe
+11  A: 

Be careful when using toFixed():

First, rounding the number is done using the binary representation of the number, which might lead to unexpected behaviour. For example

(0.595).toFixed(2) === '0.59'

instead of '0.6'.

Second, there's an IE bug with toFixed(). In IE (at least up to version 7, didn't check IE8), the following holds true:

(0.9).toFixed(0) === '0'

It might be a good idea to follow kkyy's suggestion or to use a custom toFixed() function, eg

function toFixed(value, precision) {
    var power = Math.pow(10, precision || 0);
    return String(Math.round(value * power) / power);
}
Christoph
+1 This is the most thorough and predictable solution!
Jagd
Yes, this can be very important when creating code to predict prices. Thanks! +1
Fabio Milheiro