I am trying to convert a EU formatted currency amount, say 1.243,51 (equals 1,243.51 in US formatting), to a number in javascript (that would be 1243.51).
I managed to find a large number of examples trying to do very similar things, but I've not been able to adapt it. It seems I need to use regex, which I donøt have much understanding of, but I managed to find some suggestions that almost does the task. I found one regex that replaces the "," with a "." and one which removes ".". I figured I had to do it in two steps, but the problem is that the one which removes "."s also truncates the number behind the dot. This is what I came up with so far:
function usToEuCurrencyFormat(input) {
var output = input.replace(/\./g, ''); //Removes dots
output = input.replace((/,([^,]*)$/, ".$1")); //Replaces mas with dots
return parseFloat(output);
}
I am trying to convert a EU formatted currency amount, say 1.243,51 (equals 1,243.51 in US formatting), to a number in javascript (that would be 1243.51).
I managed to find a large number of examples trying to do very similar things, but I've not been able to adapt it. It seems I need to use regex, which I donøt have much understanding of, but I managed to find some suggestions that almost does the task. I found one regex that replaces the "," with a "." and one which removes ".". I figured I had to do it in two steps, but the problem is that the one which removes "."s also truncates the number behind the dot. This is what I came up with so far:
function usToEuCurrencyFormat(input) {
var output = input.replace(/\./g, ''); //Removes dots
output = input.replace((/,([^,]*)$/, ".$1")); //Replaces mas with dots
return parseFloat(output);
}
Share
Improve this question
asked Sep 29, 2012 at 9:56
zkwskzkwsk
2,1366 gold badges31 silver badges35 bronze badges
1 Answer
Reset to default 7function usToEuCurrencyFormat(input) {
return input.replace(/[,.]/g, function (x) { return x == "," ? "." : ","; }); }
}
This seems to work well enough for me (and just parseFloat
it if you want a float).