How can I parse a string with a comma thousand separator to a number?

后端 未结 16 2801
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 10:18

I have 2,299.00 as a string and I am trying to parse it to a number. I tried using parseFloat, which results in 2. I guess the comma is the problem

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 10:46

    Usually you should consider to use input fields which don't allow free text input for numeric values. But there might be cases, when you need to guess the input format. For example 1.234,56 in Germany means 1,234.56 in US. See https://salesforce.stackexchange.com/a/21404 for a list of countries which use comma as decimal.

    I use the following function to do a best guess and strip off all non-numeric characters:

    function parseNumber(strg) {
        var strg = strg || "";
        var decimal = '.';
        strg = strg.replace(/[^0-9$.,]/g, '');
        if(strg.indexOf(',') > strg.indexOf('.')) decimal = ',';
        if((strg.match(new RegExp("\\" + decimal,"g")) || []).length > 1) decimal="";
        if (decimal != "" && (strg.length - strg.indexOf(decimal) - 1 == 3) && strg.indexOf("0" + decimal)!==0) decimal = "";
        strg = strg.replace(new RegExp("[^0-9$" + decimal + "]","g"), "");
        strg = strg.replace(',', '.');
        return parseFloat(strg);
    }   
    

    Try it here: https://plnkr.co/edit/9p5Y6H?p=preview

    Examples:

    1.234,56 € => 1234.56
    1,234.56USD => 1234.56
    1,234,567€ => 1234567
    1.234.567 => 1234567
    1,234.567 => 1234.567
    1.234 => 1234 // might be wrong - best guess
    1,234 => 1234 // might be wrong - best guess
    1.2345 => 1.2345
    0,123 => 0.123
    

    The function has one weak point: It is not possible to guess the format if you have 1,123 or 1.123 - because depending on the locale format both might be a comma or a thousands-separator. In this special case the function will treat separator as a thousands-separator and return 1123.

提交回复
热议问题