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

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

    On modern browsers you can use the built in Intl.NumberFormat to detect the browser's number formatting and normalize the input to match.

    function parseNumber(value, locales = navigator.languages) {
      const example = Intl.NumberFormat(locales).format('1.1');
      const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
      const cleaned = value.replace(cleanPattern, '');
      const normalized = cleaned.replace(example.charAt(1), '.');
    
      return parseFloat(normalized);
    }
    
    const corpus = {
      '1.123': {
        expected: 1.123,
        locale: 'en-US'
      },
      '1,123': {
        expected: 1123,
        locale: 'en-US'
      },
      '2.123': {
        expected: 2123,
        locale: 'fr-FR'
      },
      '2,123': {
        expected: 2.123,
        locale: 'fr-FR'
      },
    }
    
    
    for (const candidate in corpus) {
      const {
        locale,
        expected
      } = corpus[candidate];
      const parsed = parseNumber(candidate, locale);
    
      console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
    }

    Their's obviously room for some optimization and caching but this works reliably in all languages.

提交回复
热议问题