Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I'm using toLocaleString() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString to convert into a dollar string format, but I'm having trouble reversing the operation. In my case converting back into cents.

dollarString.split('$')[1] * 100 Messes up as soon as the string has a , in it.

Is there a better way to handle this, than to go through strings removing commas?

What if I end up using other currencies. Can't I convert in and out of whatever the currency is into a cents representation so I can do math, and then back into some locale?

like image 654
Costa Michailidis Avatar asked Jan 28 '17 01:01

Costa Michailidis


People also ask

How do I convert a string back to a number?

The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number.

What is toLocaleString () in JavaScript?

The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .

How do I localize a number in JavaScript?

In JavaScript, toLocaleString() is a Number method that is used to convert a number into a locale-specific numeric representation of the number (rounding the result where necessary) and return its value as a string.


1 Answers

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

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

The above uses a regular expression to remove everything but digits and the decimal. The parsefloat function will do the rest.

Just be careful. Some countries do not use comma and decimal the way you do! It is probably best to keep the monetary amount in a float variable, and only format it when actually printing it.

like image 100
John Wu Avatar answered Oct 28 '22 03:10

John Wu