I am using javascript and I’ve seen some ways to convert a currency to a number, but not one that is flexible to understand multiple input formats (decimal separator changes based on the user preference).
Let me show what I mean:
Some possible inputs (String or Number):
- "1.000,50"
- "$1.000,50"
- "1,000.50"
- "$1,000.50"
- 1000.50
Output (Number):
- 1000.50
3
Answers
You can check if the input is a number or a string. If it is a number, return it immediately. If it is a string, detect the number format and replace characters as necessary, and return the converted number.
Here is a more-robust solution that checks for
NaN
as well:In the snippet below I’m copying the String that you have, ignoring $ and, if it’s . or , then I’m ignoring it unless it’s at the end of the String.
For this I Found this Solutions lets try
output : [1.0005, 1.0005, 1000.5, 1000.5, 1000.5, 1000.5]