Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript parseFloat '500,000' returns 500 when I need 500000

How would it be a nice way of handling this?

I already thought on removing the comma and then parsing to float.

Do you know a better/cleaner way?

Thanks

like image 326
DanC Avatar asked Jul 08 '10 16:07

DanC


People also ask

What does the parseFloat () method does in JavaScript?

The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number.

How do you round parseFloat 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. Parameters: String: The floating-point number in the string format that is to be parsed.

What happens if you parseFloat a number?

parseFloat() method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns NaN .

How do you use commas with parseFloat?

If you want parse a number (float number) string with commas thousand separators into a number by removing the commas, and then use the + operator to do the conversion. You can do it with parseFloat method and replace method.


2 Answers

parseFloat( theString.replace(/,/g,'') ); 
like image 83
James Avatar answered Sep 22 '22 14:09

James


I don't know why no one has suggested this expression-

parseFloat( theString.replace(/[^\d\.]/g,'') ); 

Removes any non-numeric characters except for periods. You don't need custom functions/loops for this either, that's just overkill.

like image 34
micah Avatar answered Sep 22 '22 14:09

micah