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?
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With