最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to convert EU number formatting to a javascript number with regex - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 7
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).

发布评论

评论列表(0)

  1. 暂无评论