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

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

提交回复
热议问题