Does JavaScript take local decimal separators into account?

前端 未结 7 800
陌清茗
陌清茗 2020-12-10 06:26

I\'ve got a web page that displays decimals in a user\'s localized format, like so:

  • English: 7.75
  • Dutch: 7,75

相关标签:
7条回答
  • 2020-12-10 07:16

    Expanding on the solution from @OXiGEN we can use Intl.NumberFormat.formatToParts() to extract also the currency symbol :)

    function parseLocaleNumber(stringNumber, locale, currency_code) {
      let num = 123456.789,
        fmt_local = new Intl.NumberFormat(locale, {
          style: 'currency',
          currency: currency_code
        }),
        parts_local = fmt_local.formatToParts(num),
        group = '',
        decimal = '',
        currency = '';
    
      // separators
      parts_local.forEach(function(i) {
        //console.log(i.type + ':' + i.value);
        switch (i.type) {
          case 'group':
            group = i.value;
            break;
          case 'decimal':
            decimal = i.value;
            break;
          case 'currency':
            currency = i.value;
            break;
          default:
            break;
        }
      });
    
      return parseFloat(stringNumber
        .replace(new RegExp('\\' + group, 'g'), '')
        .replace(new RegExp('\\' + decimal), '.')
        .replace(new RegExp('\\' + currency, 'g'), '')
      );
    }
    
    //replace inputs with a number formatted for your locale, your locale code, your currency code
    console.log(parseLocaleNumber('$987,654,321.01', 'en', 'USD'));
    //output for "en" locale and "USD" code: 987654321.01

    0 讨论(0)
提交回复
热议问题