Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: Convert string X,XXX.XX to float

I'm bothering you because I'm looking to convert a string into a float with node.JS. I have a string that comes back from a request and looks like: x,xxx.xxxx (ex. 4,530.1200) and I'd like to convert it to a float: xxxx.xxxx (or 4530.1200). I've tried to use: parseFloat(str) but it returns 4. I also found Float.valueOf(str) on the web but I get a ReferenceError: Float is not defined error.

like image 817
Ardzii Avatar asked Nov 20 '25 01:11

Ardzii


1 Answers

You can use string replace to solve this kind of problem.

str = '4,530.1200';
parseFloat(str.replace(/,/g, ''));

This will remove all the , from your string so that you can convert it to the float using parseFloat.

Notice the g flag in regex, it represents global, by using this you are specifying to remove all the matched regex.

like image 165
Raghav Garg Avatar answered Nov 22 '25 17:11

Raghav Garg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!