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

后端 未结 16 2933
被撕碎了的回忆
被撕碎了的回忆 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: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);
    }
    

提交回复
热议问题