Home > Software design >  How can I handle float number correctly in JS?
How can I handle float number correctly in JS?

Time:09-27

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?

CodePudding user response:

You have to remove comma first and use parseFloat.

And about 2 decimal after dot, I see you use number_format($myNumber, 2) in PHP, so in JS, you use .toFixed(2).

var number = '2,206.00';
var result = parseFloat(number.replace(/,/g, '')).toFixed(2);
console.log(result);

CodePudding user response:

First of all what you currently have most probably would trigger an Unexpected number error in JS.

It seems the generated value comes from the number_format() PHP function which returns a string. Moreover the var number variable should also be considered a string as we have a string format.

So firstly you should quote var number = '2,206.00' after that, you have to make the string float-like in order to parse it as float so we should replace , with empty string in order for the number to become 2206.00 number = number.replace(",",""). Lastly the parse should be done now in order to convert the float-like string to an actual float parseFloat(number).

Whole code:

var number = '2,206.00';
number.replace(",","");
number = parseFloat(number);

CodePudding user response:

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 before parsing it.

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

CodePudding user response:

ok, basically you want a two decimal number after point like (20.03), try this

parseFloat(number).toFixed(2)
  • Related