Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript parseFloat in Different Cultures

I have a question about the default behavior of JavaScript's parseFloat function in different parts of the world.

In the US, if you call parseFloat on a string "123.34", you'd get a floating point number 123.34.

If I'm developing code in say Sweden or Brazil and they use a comma instead of a period as the decimal separator, does the parseFloat function expect "123,34" or "123.34".

Please note that I'm not asking how to parse a different culture's number format in the US. I'm asking does parseFloat in Sweden or Brazil behave the same way it does inside the US, or does it expect a number in its local format? Or to better think about this, does a developer in Brazil/Sweden have to convert strings to English format before it can use parseFloat after extracting text from a text box?

Please let me know if this doesn't make sense.

like image 331
chumphries Avatar asked Oct 02 '12 16:10

chumphries


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.

What is the difference between parseFloat and number JavaScript?

parseFloat is a bit slower because it searches for first appearance of a number in a string, while the Number constuctor creates a new number instance from strings that contains numeric values with whitespace or that contains falsy values.

What is the difference between parseInt and parseFloat in JavaScript?

parseInt is for converting a non integer number to an int and parseFloat is for converting a non float (with out a decimal) to a float (with a decimal). If your were to get input from a user and it comes in as a string you can use the parse method to convert it to a number that you can perform calculations on.

Is parseFloat a method?

The parseFloat() method in Float Class is a built in method in Java that returns a new float initialized to the value represented by the specified String, as done by the valueOf method of class Float. Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.


2 Answers

parseFloat doesn't use your locale's definition, but the definition of a decimal literal.

It only parses . not ,

I'm brazilian and I have to replace comma with dot before parsing decimal numbers.

parseFloat specification

like image 159
Alcides Queiroz Avatar answered Sep 19 '22 14:09

Alcides Queiroz


No, parseFloat is specified to parse DecimalLiterals, which use the dot as decimal separator. It does not depend on the current environment's locale settings.

like image 37
Bergi Avatar answered Sep 19 '22 14:09

Bergi