Search code examples
javascriptparsefloat

How can I handle float number correctly in JS?


In JS, I do have a float number which come from php as below:

var number = 2,206.00

In JS, I need to use parseFloat that number.

So I tried parseFloat(number), but its give only 2. So how can I get 2206.00 instead of 2?


Solution

  • Number.parseFloat is the same function object as globalThis.parseFloat.

    If globalThis.parseFloat encounters a character other than:

    • a plus sign or,
    • a minus sign or,
    • a decimal point or,
    • an exponent (E or e)

    ...it returns the value up to that character, ignoring the invalid character and characters following it. A second decimal point also stops parsing.

    So the following prints 2. And this seems to be your problem.

    console.log(parseFloat('2,206.00')) // 2

    Solution: use string manipulation to remove any commas from the number (really a String before parsing it.

    console.log(parseFloat('2,206.00'.replaceAll(',', ''))) // 2206

    If you need to store the value as a number but render it as a formatted string, you may need Number#toFixed to render the values after the decimal point:

    console.log((2206).toFixed(2)) // '2206.00'

    Final note: be careful about localization because some countries use commas for decimal points and decimal points for number grouping. As @t.niese says: store number values without localization, and then apply localization at the surface of your app. But that is a wider, more complicated topic.