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

后端 未结 16 2585
被撕碎了的回忆
被撕碎了的回忆 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:21

    Remove anything that isn't a digit, decimal point, or minus sign (-):

    var str = "2,299.00";
    str = str.replace(/[^\d\.\-]/g, ""); // You might also include + if you want them to be able to type it
    var num = parseFloat(str);
    

    Updated fiddle

    Note that it won't work for numbers in scientific notation. If you want it to, change the replace line to add e, E, and + to the list of acceptable characters:

    str = str.replace(/[^\d\.\-eE+]/g, "");
    
    0 讨论(0)
  • 2020-11-22 10:24
    Number("2,299.00".split(',').join(''));   // 2299
    
    

    The split function splits the string into an array using "," as a separator and returns an array.
    The join function joins the elements of the array returned from the split function.
    The Number() function converts the joined string to a number.

    0 讨论(0)
  • 2020-11-22 10:25

    This is a simplistic unobtrusive wrapper around the parseFloat function.

    function parseLocaleNumber(str) {
      // Detect the user's locale decimal separator:
      var decimalSeparator = (1.1).toLocaleString().substring(1, 2);
      // Detect the user's locale thousand separator:
      var thousandSeparator = (1000).toLocaleString().substring(1, 2);
      // In case there are locales that don't use a thousand separator
      if (thousandSeparator.match(/\d/))
        thousandSeparator = '';
    
      str = str
        .replace(new RegExp(thousandSeparator, 'g'), '')
        .replace(new RegExp(decimalSeparator), '.')
    
      return parseFloat(str);
    }
    
    0 讨论(0)
  • 2020-11-22 10:28

    With this function you will be able to format values in multiple formats like 1.234,56 and 1,234.56, and even with errors like 1.234.56 and 1,234,56

    /**
     * @param {string} value: value to convert
     * @param {bool} coerce: force float return or NaN
     */
    function parseFloatFromString(value, coerce) {
        value = String(value).trim();
    
        if ('' === value) {
            return value;
        }
    
        // check if the string can be converted to float as-is
        var parsed = parseFloat(value);
        if (String(parsed) === value) {
            return fixDecimals(parsed, 2);
        }
    
        // replace arabic numbers by latin
        value = value
        // arabic
        .replace(/[\u0660-\u0669]/g, function(d) {
            return d.charCodeAt(0) - 1632;
        })
    
        // persian
        .replace(/[\u06F0-\u06F9]/g, function(d) {
            return d.charCodeAt(0) - 1776;
        });
    
        // remove all non-digit characters
        var split = value.split(/[^\dE-]+/);
    
        if (1 === split.length) {
            // there's no decimal part
            return fixDecimals(parseFloat(value), 2);
        }
    
        for (var i = 0; i < split.length; i++) {
            if ('' === split[i]) {
                return coerce ? fixDecimals(parseFloat(0), 2) : NaN;
            }
        }
    
        // use the last part as decimal
        var decimal = split.pop();
    
        // reconstruct the number using dot as decimal separator
        return fixDecimals(parseFloat(split.join('') +  '.' + decimal), 2);
    }
    
    function fixDecimals(num, precision) {
        return (Math.floor(num * 100) / 100).toFixed(precision);
    }
    
    parseFloatFromString('1.234,56')
    "1234.56"
    parseFloatFromString('1,234.56')
    "1234.56"
    parseFloatFromString('1.234.56')
    "1234.56"
    parseFloatFromString('1,234,56')
    "1234.56"
    
    0 讨论(0)
  • 2020-11-22 10:31

    Replace the comma with an empty string:

    var x = parseFloat("2,299.00".replace(",",""))
    alert(x);

    0 讨论(0)
  • 2020-11-22 10:32

    It's baffling that they included a toLocaleString but not a parse method. At least toLocaleString without arguments is well supported in IE6+.

    For a i18n solution, I came up with this:

    First detect the user's locale decimal separator:

    var decimalSeparator = 1.1;
    decimalSeparator = decimalSeparator.toLocaleString().substring(1, 2);
    

    Then normalize the number if there's more than one decimal separator in the String:

    var pattern = "([" + decimalSeparator + "])(?=.*\\1)";separator
    var formatted = valor.replace(new RegExp(pattern, "g"), "");
    

    Finally, remove anything that is not a number or a decimal separator:

    formatted = formatted.replace(new RegExp("[^0-9" + decimalSeparator + "]", "g"), '');
    return Number(formatted.replace(decimalSeparator, "."));
    
    0 讨论(0)
提交回复
热议问题