JavaScript 中的文化敏感 ParseFloat 函数?

发布于 2024-10-16 14:14:06 字数 153 浏览 1 评论 0 原文

有人建议在 JavaScript 中编写文化敏感的 ParseFloat 函数吗?这样,当我有美国文化格式的字符串 100,000.22 时,解析 float 函数返回 100000.22,而如果我在瑞典文化中输入 100.000,22 ,它会返回 float 形式的 100000.22 ?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

入怼 2024-10-23 14:14:06

我改进了 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);
}

I've improved mwilcox' function to handle values withous separators.

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);
}
蓝梦月影 2024-10-23 14:14:06

这有点粗糙,但可能已经足够了,允许您传递千位和小数分隔符:

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

示例:

parseFloatOpts("100.000,22", ',', '.'); //100000.22
parseFloatOpts("100,000.22", '.', ','); //100000.22

注意,这并不能确保千位分隔符确实代表千位等,或者确实代表千位分隔符。您可能希望执行许多其他保护措施,具体取决于功能的重要性。

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.

流年已逝 2024-10-23 14:14:06
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

我只是检查倒数第三个位置是否有逗号。如果您没有逗号(例如 100.000),可以进一步细化以检查倒数第四个位置是否有句点

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)

对不⑦ 2024-10-23 14:14:06

看着 lonesomday 给了我这样的想法:

你也可以这样做:

function parse (str)
    var ar = str.split(/\.|,/);  
    return Number(ar[0]+ar[1]+"."+ar[3]);

Looking at lonesomday's gave me this thought:

You could also do:

function parse (str)
    var ar = str.split(/\.|,/);  
    return Number(ar[0]+ar[1]+"."+ar[3]);
掀纱窥君容 2024-10-23 14:14:06

这是一个粗略的函数。它将假定最后一个标点符号表示小数,无论它是逗号、句点还是您可能需要表示的任何其他字符。然后它会从整个数字中删除其他标点符号。将其放回一起并解析为浮点数。

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

试试这个:

alert(normalizeFloat('12.345,77', [',','.']).toFixed(2));
alert(normalizeFloat('12,345.77', [',','.']).toFixed(2));

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));
风向决定发型 2024-10-23 14:14:06

需要来自文化信息的当前组和小数分隔符。

function escapeRegExp(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, "\\
amp;");
    }

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

Need your current Group and Decimal Separator from Culture Info.

function escapeRegExp(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, "\\
amp;");
    }

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);
    }
江心雾 2024-10-23 14:14:06

如果您确实想在 JavaScript 的不同语言环境中显示和/或解析浮点数(或日期或货币等),那么我的推荐是 GlobalizeJS (https://github.com/globalizejs/globalize)库。

一开始设置起来有点困难(至少根据我的经验),但完全建议您妥善管理此事。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文