JavaScript displaying a float to 2 decimal places

JavaScript displaying a float to 2 decimal places

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?

Solutions/Answers:

Solution 1:

float_num.toFixed(2);

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

Solution 2:

You could do it with the toFixed function, but it’s buggy in IE. If you want a reliable solution, look at my answer here.

Solution 3:

Try toFixed instead of toPrecision.

Solution 4:

Don’t know how I got to this question, but even if it’s many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:

var num = response_from_a_function_or_something();

var fixedNum = parseFloat(num).toFixed( 2 );

Solution 5:

function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

round(1.005, 2); // return 1.01

round(1.004, 2); // return 1 instead of 1.00

The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/

Related:  Maximum size of an Array in Javascript

Solution 6:

number.parseFloat(2) works but it returns a string.

If you’d like to preserve it as a number type you can use:

Math.round(number * 100) / 100