Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 877
alex Avatar asked Jul 02 '10 03:07

alex


People also ask

How do you show float to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do I print two decimal places in JavaScript?

To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.

How do I limit decimal places in JavaScript?

To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places. This method: Rounds the number. Converts it into a string.

How do you round a float in JavaScript?

Math. round() is a function used to return the value of a floating-point number rounded to the nearest whole integer. Depending on the supplied float/double, Math. round() either rounds up or down.


1 Answers

float_num.toFixed(2); 

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

like image 192
Jason McCreary Avatar answered Oct 11 '22 10:10

Jason McCreary