Reputation: 8188
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?
Upvotes: 6
Views: 8575
Reputation: 4828
Ex: I decide to use n digits after dot and comma separator
Object.defineProperties(Number.prototype,{
locale:{
value:function(n){
n = n||2
return this.toLocaleString('en', {
minimumFractionDigits: n,
maximumFractionDigits: n
});
}
}
});
/ reverse from string to number /
Object.defineProperties(String.prototype,{
floatLocale:{
value: function(){
return parseFloat(this.replace(/,/g,""));
}
}
});
So v= 1000.33; v === v.locale().floatLocale();
Upvotes: 1
Reputation:
As suggested by others, you need to remove (,
) from the string.
dollarString.split('$')[1].replace(/\,/g,'') * 100
In case,dollarString
has only values as $xx,xxx,xxx$xx,xxx,xxx
, then you may simply remove all (,
) then split
dollarString.replace(/\,/g,'').split('$')[1] * 100
Upvotes: 1
Reputation: 52280
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.
Upvotes: 4