How to convert a locale string (currency) back to a number?

I use toLocaleString() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString to convert to a string format in dollars, but I am having problems changing the operation. In my case, converting back to cents.

dollarString.split('$')[1] * 100 Placed as soon as the line contains dollarString.split('$')[1] * 100

Is there a better way to handle this than sorting through strings with commas?

What if I use other currencies. Can I convert to and from any currency into a representation of cents so that I can do the math and then return to some language?

+5
javascript
Jan 28 '17 at 1:10
source share
2 answers

Assuming you are in a locale that uses the period as a decimal point, you could use something like this:

 var dollarsAsFloat = parseFloat(dollarString.replace(/[^0-9-.]/g, '')); 

The above example uses a regular expression to remove everything except digits and decimal. The parsefloat function does the rest.

Just be careful. Some countries do not use commas or decimals like you! It is probably best to save the amount in the float variable and only format it when printing it. A.

+4
Jan 28 '17 at 1:18
source share

As suggested by others, you need to remove ( , ) from the string.

 dollarString.split('$')[1].replace(/\,/g,'') * 100 

In case dollarString only has values ​​like $xx,xxx,xxx$xx,xxx,xxx , you can just delete everything ( , ) and then split

 dollarString.replace(/\,/g,'').split('$')[1] * 100 
+1
Jan 28 '17 at 1:39 on
source share



All Articles