Question

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 commas with dots
    return parseFloat(output);
}
Was it helpful?

Solution

function 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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top