如何使用正则表达式将EU号格式转换为javascript号 [英] How to convert EU number formatting to a javascript number with regex

查看:116
本文介绍了如何使用正则表达式将EU号格式转换为javascript号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将欧盟格式的货币金额(例如1.243,51(等于美国格式的1,243.51))转换为javascript中的数字(即1243.51).

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);
}

推荐答案

function usToEuCurrencyFormat(input) {
    return input.replace(/[,.]/g, function (x) { return x == "," ? "." : ","; }); }
}

这对我来说似乎已经足够好了(如果想要浮动,只需parseFloat即可).

This seems to work well enough for me (and just parseFloat it if you want a float).

这篇关于如何使用正则表达式将EU号格式转换为javascript号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆