# How to format a float in javascript?

## How to format a float in javascript?

In JavaScript, when converting from a float to a string, how can I get just 2 digits after the decimal point? For example, 0.34 instead of 0.3445434.

### Solution 1:

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 🙂

### Solution 2:

There are functions to round numbers. For example:

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

will print 5.04.

EDIT:
Fiddle

### Solution 3:

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'

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);
}

### Solution 4:

One more problem to be aware of, is that toFixed() can produce unnecessary zeros at the end of the number.
For example:

var x=(23-7.37)
x
15.629999999999999
x.toFixed(6)
"15.630000"

The idea is to clean up the output using a RegExp:

function humanize(x){
return x.toFixed(6).replace(/\.?0*\$/,'');
}

The RegExp matches the trailing zeros (and optionally the decimal point) to make sure it looks good for integers as well.

humanize(23-7.37)
"15.63"
humanize(1200)
"1200"
humanize(1200.03)
"1200.03"
humanize(3/4)
"0.75"
humanize(4/3)
"1.333333"

### Solution 5:

var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding

### Solution 6:

There is a problem with all those solutions floating around using multipliers. Both kkyy and Christoph’s solutions are wrong unfortunately.

Please test your code for number 551.175 with 2 decimal places – it will round to 551.17 while it should be 551.18 ! But if you test for ex. 451.175 it will be ok – 451.18. So it’s difficult to spot this error at a first glance.

The problem is with multiplying: try 551.175 * 100 = 55117.49999999999 (ups!)

So my idea is to treat it with toFixed() before using Math.round();

function roundFix(number, precision)
{
var multi = Math.pow(10, precision);
return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
}