JavaScript displaying a float to 2 decimal places

alex picture alex · Jul 2, 2010 · Viewed 367.5k times · Source

I wanted to display a number to 2 decimal places.

I thought I could use toPrecision(2) in JavaScript .

However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.

See it on JSbin.

What is the best way to do this?

I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?

Answer

Jason McCreary picture Jason McCreary · Jul 2, 2010
float_num.toFixed(2);

Note:toFixed() will round or pad with zeros if necessary to meet the specified length.