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

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

    If you want to avoid the problem that David Meister posted and you are sure about the number of decimal places, you can replace all dots and commas and divide by 100, ex.:

    var value = "2,299.00";
    var amount = parseFloat(value.replace(/"|\,|\./g, ''))/100;
    

    or if you have 3 decimals

    var value = "2,299.001";
    var amount = parseFloat(value.replace(/"|\,|\./g, ''))/1000;
    

    It's up to you if you want to use parseInt, parseFloat or Number. Also If you want to keep the number of decimal places you can use the function .toFixed(...).

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

    Yes remove the commas:

    parseFloat(yournumber.replace(/,/g, ''));
    
    0 讨论(0)
  • 2020-11-22 10:41

    All of these answers fail if you have a number in the millions.

    3,456,789 would simply return 3456 with the replace method.

    The most correct answer for simply removing the commas would have to be.

    var number = '3,456,789.12';
    number.split(',').join('');
    /* number now equips 3456789.12 */
    parseFloat(number);
    

    Or simply written.

    number = parseFloat(number.split(',').join(''));
    
    0 讨论(0)
  • 2020-11-22 10:44

    Removing commas is potentially dangerous because, as others have mentioned in the comments, many locales use a comma to mean something different (like a decimal place).

    I don't know where you got your string from, but in some places in the world "2,299.00" = 2.299

    The Intl object could have been a nice way to tackle this problem, but somehow they managed to ship the spec with only a Intl.NumberFormat.format() API and no parse counterpart :(

    The only way to parse a string with cultural numeric characters in it to a machine recognisable number in any i18n sane way is to use a library that leverages CLDR data to cover off all possible ways of formatting number strings http://cldr.unicode.org/

    The two best JS options I've come across for this so far:

    • https://github.com/google/closure-library/tree/master/closure/goog/i18n
    • https://github.com/globalizejs/globalize
    0 讨论(0)
  • 2020-11-22 10:45
    const parseLocaleNumber = strNum => {
        const decSep = (1.1).toLocaleString().substring(1, 2);
        const formatted = strNum
            .replace(new RegExp(`([${decSep}])(?=.*\\1)`, 'g'), '')
            .replace(new RegExp(`[^0-9${decSep}]`, 'g'), '');
        return Number(formatted.replace(decSep, '.'));
    };
    
    0 讨论(0)
  • 2020-11-22 10:45

    If you have a small set of locales to support you'd probably be better off by just hardcoding a couple of simple rules:

    function parseNumber(str, locale) {
      let radix = ',';
      if (locale.match(/(en|th)([-_].+)?/)) {
        radix = '.';
      }
      return Number(str
        .replace(new RegExp('[^\\d\\' + radix + ']', 'g'), '')
        .replace(radix, '.'));
    }
    
    0 讨论(0)
提交回复
热议问题