简体   繁体   中英

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?

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.

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);

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);

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

parseFloat(number).toFixed(2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM