I am trying to parse two values from a datagrid.
The fields are numeric, and when they have a comma (ex. 554,20), I can't get the numbers after the comma.
I've tried parseInt
and parseFloat
. How can I do this?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Correctly parse PDF paragraphs with Python
- Keeping track of variable instances
I had the same problem except I did not know in advance what were the thousands separators and the decimal separator. I ended up writing a library to do this. If you are interested it here it is : https://github.com/GuillaumeLeclerc/number-parsing
If they're meant to be separate values, try this:
If they're meant to be a single value (like in French, where one-half is written 0,5)
@GusDeCool or anyone else trying to replace more than one thousands separators, one way to do it is a regex global replace:
/foo/g
. Just remember that.
is a metacharacter, so you have to escape it or put it in brackets (\.
or[.]
). Here's one option:Replace the comma with a dot.
This will only return 554:
This will return 554.20:
So in the end, you can simply use:
Don't forget that
parseInt()
should only be used to parse integers (no floating points). In your case it will only return 554. Additionally, calling parseInt() on a float will not round the number: it will take its floor (closest lower integer).Extended example to answer Pedro Ferreira's question from the comments:
If the textfield contains thousands separator dots like in
1.234.567,99
those could be eliminated beforehand with anotherreplace
:You can use this function. It will replace the commas with ' ' and then it will parseFlaot the value and after that it will again adjust the commas in value.
Have you ever tried to do this? :p
+(string) will cast string into float.
Handy!
So in order to solve your problem, you can do something like this: