Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse float with two decimal places in javascript?

I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00. Or if it equals 10.6 would be 10.60. Not sure how to do this.

price_result = parseFloat(test_var.split('$')[1].slice(0,-1)); 
like image 858
user357034 Avatar asked Dec 14 '10 01:12

user357034


People also ask

How do I get 2 decimal places in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

How do you make a 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 %.

Is float 2 decimal places?

format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do I use parseFloat and toFixed in JavaScript?

To parse a float with 2 decimal places:Pass the float to the parseFloat() function. Use the toFixed() method to format the float to 2 decimal places. The toFixed method will return a string representation of the number formatted to 2 decimal places.


2 Answers

You can use toFixed() to do that

var twoPlacedFloat = parseFloat(yourString).toFixed(2) 
like image 164
Mahesh Velaga Avatar answered Oct 08 '22 02:10

Mahesh Velaga


If you need performance (like in games):

Math.round(number * 100) / 100 

It's about 100 times as fast as parseFloat(number.toFixed(2))

http://jsperf.com/parsefloat-tofixed-vs-math-round

like image 41
Rob Boerman Avatar answered Oct 08 '22 03:10

Rob Boerman