3

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Martin Carre
  • 1,157
  • 4
  • 20
  • 42
  • 1
    I would use string replace to go around this problem like: `parseFloat('4,530.1200'.replace(/,/g, ''))`. – Raghav Garg Aug 19 '17 at 13:41
  • Thanks a lot! I was hopping for an existing more direct approach than getting into regex manip' but I worked like a charm so thanks again! If you want, put it up as an answer so that I can reference it as the solution! – Martin Carre Aug 19 '17 at 13:44
  • 3
    Just a tip: don't use floating point numbers to represent currency. – robertklep Aug 19 '17 at 13:48
  • Hmmmm ... ok... :P Why is that (if you have the time to explain)? and what should I use? FYI. The info is being recieved from a request, then manipulated into a specific layout (still an object) and then sent to a mongodb via mongoose. – Martin Carre Aug 19 '17 at 13:50
  • 1
    Read this: https://stackoverflow.com/a/3730040 For Mongoose, there are specific plugins that handle currency values, like [`mongoose-currency`](https://github.com/paulcsmith/mongoose-currency) – robertklep Aug 19 '17 at 13:53

1 Answers1

6

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.

Raghav Garg
  • 3,601
  • 2
  • 23
  • 32