Reputation: 2936
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?
Upvotes: 0
Views: 693
Reputation: 55779
Number.parseFloat
is the same function object as globalThis.parseFloat
.
If globalThis.parseFloat
encounters a character other than:
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.
Upvotes: 3
Reputation: 165
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);
Upvotes: 1
Reputation: 2815
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);
Upvotes: 1