如何将区域设置字符串(货币)转换回数字? [英] How to convert a locale string (currency) back into a number?

查看:96
本文介绍了如何将区域设置字符串(货币)转换回数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 toLocaleString() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString 转换为美元字符串格式,但我无法撤消操作。在我的情况下转换回美分。

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 字符串有一个字符串其中包含

dollarString.split('$')[1] * 100 Messes up as soon as the string has a , in it.

有没有更好的方法来解决这个问题,而不是去除字符串逗号?

如果我最终使用其他货币该怎么办?我不能将货币兑换成美分代表,这样我就可以做数学,然后再回到某个地方?

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?

推荐答案

假设您所在的区域设置使用句点作为小数点,您可以使用以下内容:

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, '')); 

上面使用正则表达式删除除数字和小数之外的所有内容。 parsefloat 函数将完成剩下的工作。

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.

这篇关于如何将区域设置字符串(货币)转换回数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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