JavaScript 中的文化敏感 ParseFloat 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4951738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Culture sensitive ParseFloat Function in JavaScript?
提问by Faheem Ramzan
Do anyone have suggestion for writing culture sensitive ParseFloat Function in JavaScript, So that when I have a string 100,000.22 in US culture format the parse float function returns 100000.22 whereas if I enter 100.000,22 in Swedish Culture it returns 100000.22 in float?
有没有人建议在 JavaScript 中编写对文化敏感的 ParseFloat 函数,这样当我在美国文化格式中有一个字符串 100,000.22 时,解析浮点函数返回 100000.22 而如果我在瑞典文化中输入 100.000,22 它返回 100000.22 浮点数?
回答by Alex Polishchuk
I've improved mwilcox' function to handle values withous separators.
我改进了 mwilcox 函数来处理没有分隔符的值。
function parseFloatOpts (str) {
if(typeof str === "number"){
return str;
}
var ar = str.split(/\.|,/);
var value = '';
for (var i in ar) {
if (i>0 && i==ar.length-1) {
value += ".";
}
value +=ar[i];
}
return Number(value);
}
回答by lonesomeday
This is a bit rough-and-ready, but it may be sufficient, allowing you to pass in the thousands and decimal separators:
这有点粗略,但它可能就足够了,允许您传入千位和小数分隔符:
function parseFloatOpts(num, decimal, thousands) {
var bits = num.split(decimal, 2),
ones = bits[0].replace(new RegExp('\' + thousands, 'g'), '');
ones = parseFloat(ones, 10),
decimal = parseFloat('0.' + bits[1], 10);
return ones + decimal;
}
Examples:
例子:
parseFloatOpts("100.000,22", ',', '.'); //100000.22
parseFloatOpts("100,000.22", '.', ','); //100000.22
NB that this doesn't ensure that the thousands separator really does represent thousands, etc., or do lots of other safeguarding that you may wish to do, depending on the importance of the function.
注意,这并不能确保千位分隔符确实代表千位等,或者根据功能的重要性进行您可能希望做的许多其他保护。
回答by mwilcox
var parse = function(st){
if(st.indexOf(",") === st.length-3){
st = st.replace(".", "").replace(",", ".");
}else{
st = st.replace(",", "");
}
return parseFloat(st, 10)
}
console.log(parse("100,000.22")) // 100000.22
console.log(parse("100.000,22")) // 100000.22
I'm just checking if there is a comma in the 3rd-to-last position. This could be further refined to check if there is a period in the 4th to last position in the case thee is no comma (such as 100.000)
我只是检查倒数第三个位置是否有逗号。如果您没有逗号(例如 100.000),则可以进一步细化以检查从第 4 个到最后一个位置是否有句点
回答by mwilcox
Looking at lonesomday's gave me this thought:
看着 lonesomday's 给了我这个想法:
You could also do:
你也可以这样做:
function parse (str)
var ar = str.split(/\.|,/);
return Number(ar[0]+ar[1]+"."+ar[3]);
回答by Victor
Here is a rough function. It will assume the last punctuation to indicate decimals, whether it is a comma, period, or any other character you may need to indicate. It then eliminates other punctuations from the whole number. Puts it back together and parses as float.
这是一个粗略的函数。它将假定最后一个标点符号表示小数,无论是逗号、句点还是您可能需要表示的任何其他字符。然后从整数中消除其他标点符号。将它放回一起并解析为浮点数。
function normalizeFloat(number, chars) {
var lastIndex = -1;
for(i=0; i < chars.length; i++) {
t = number.lastIndexOf(chars[i]);
if (t > lastIndex) {
lastIndex = t;
}
}
if (lastIndex == -1) {
lastIndex = number.length;
}
var whole = number.substring(0, lastIndex);
var precision = number.substring(lastIndex);
for (i=0; i < chars.length; i++) {
whole = whole.replace(chars[i], '');
precision = precision.replace(chars[i],'.');
}
number = whole + precision;
f = parseFloat(number);
return f;
}
try this:
试试这个:
alert(normalizeFloat('12.345,77', [',','.']).toFixed(2));
alert(normalizeFloat('12,345.77', [',','.']).toFixed(2));
回答by Hitesh Patel
Need your current Group and Decimal Separator from Culture Info.
需要来自 Culture Info 的当前组和小数分隔符。
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\]/g, "\$&");
}
function parseFloatOpts(str, groupSeparator, decimalSeparator) {
if (typeof str === "number") {
return str;
}
var value = str.replace(new RegExp(escapeRegExp(groupSeparator), 'g'), "");
value = value.replace(decimalSeparator, ".");
return Number(value);
}
回答by xarlymg89
If you really for displaying and/or parsing floats (or dates or currencies or more) in different locales for JavaScript, then my recommendation is the GlobalizeJS (https://github.com/globalizejs/globalize) library.
如果您真的要在 JavaScript 的不同语言环境中显示和/或解析浮点数(或日期或货币或更多),那么我的建议是 GlobalizeJS ( https://github.com/globalizejs/globalize) 库。
It's a bit tough to set up at first (at least it was in my experience), but totally recommended for proper management of this matter.
起初设置有点困难(至少根据我的经验),但完全建议正确管理此事。

