![](/img/trans.png)
[英]How to format a big number (represented by string) in JavaScript with currency and with respect to the locale?
[英]How to convert a locale string (currency) back into a number?
我正在使用toLocaleString()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString转换为美元字符串格式,但我无法反转手术。 在我的情况下,转换回美分。
dollarString.split('$')[1] * 100
只要字符串中有,
就dollarString.split('$')[1] * 100
了。
有没有比通过字符串删除逗号更好的方法来处理这个问题?
如果我最终使用其他货币怎么办。 我不能将任何货币转换成美分表示,这样我就可以做数学,然后再转换回某些语言环境吗?
假设您在使用句点作为小数点的语言环境中,您可以使用以下内容:
var dollarsAsFloat = parseFloat(dollarString.replace(/[^0-9-.]/g, ''));
以上使用正则表达式删除除数字和小数以外的所有内容。 parsefloat
函数将完成剩下的工作。
小心点。 有些国家/地区不像您那样使用逗号和小数! 最好将货币金额保留在浮点变量中,并且仅在实际打印时对其进行格式化。
正如其他人所建议的那样,您需要从字符串中删除 ( ,
)。
dollarString.split('$')[1].replace(/\,/g,'') * 100
在情况下, dollarString
只值$xx,xxx,xxx$xx,xxx,xxx
,你可以简单地删除所有( ,
)再拆
dollarString.replace(/\,/g,'').split('$')[1] * 100
例如:我决定在点和逗号分隔符后使用 n 位数字
Object.defineProperties(Number.prototype,{
locale:{
value:function(n){
n = n||2
return this.toLocaleString('en', {
minimumFractionDigits: n,
maximumFractionDigits: n
});
}
}
});
/ 从字符串反转为数字 /
Object.defineProperties(String.prototype,{
floatLocale:{
value: function(){
return parseFloat(this.replace(/,/g,""));
}
}
});
所以v= 1000.33; v === v.locale().floatLocale();
v= 1000.33; v === v.locale().floatLocale();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.