Skip to content Skip to sidebar Skip to footer

Does Javascript Take Local Decimal Separators Into Account?

I've got a web page that displays decimals in a user's localized format, like so: English: 7.75 Dutch: 7,75 If I add two number variables together in JavaScript on my machine (wh

Solution 1:

Here's an example for a locale aware number parser:

functionparseLocaleNumber(stringNumber, locale) {
    var thousandSeparator = Intl.NumberFormat(locale).format(11111).replace(/\p{Number}/gu, '');
    var decimalSeparator = Intl.NumberFormat(locale).format(1.1).replace(/\p{Number}/gu, '');

    returnparseFloat(stringNumber
        .replace(newRegExp('\\' + thousandSeparator, 'g'), '')
        .replace(newRegExp('\\' + decimalSeparator), '.')
    );
}

It uses the passed locale (or the current locale of the browser if locale parameter is undefined) to replace thousand and decimal separators.

With a German locale setting

var n = parseLocaleNumber('1.000.045,22');

n will be equal to 1000045.22.

Update:

  • Addressed Pointy's comment by using the regex class \p{Number} for removing digits. So that it also works with non-arabic digits.
  • Addressed Orion Adrian's comment to support languages where numbers are separated at every fourth digits.
  • Added locale parameter to sepcify different locales for parsing.

Solution 2:

No, the separator is always a dot (.) in a javascript Number. So 7,75 evaluates to 75, because a , invokes left to right evaluation (try it in a console: x=1,x+=1,alert(x), or more to the point var x=(7,75); alert(x);). If you want to convert a Dutch (well, not only Dutch, let's say Continental European) formatted value, it should be a String. You could write an extension to the String prototype, something like:

String.prototype.toFloat = function(){
      returnparseFloat(this.replace(/,(\d+)$/,'.$1'));
};
//usage'7,75'.toFloat()+'7,75'.toFloat(); //=> 15.5

Note, if the browser supports it you can use Number.toLocaleString

console.log((3.32).toLocaleString("nl-NL"));
console.log((3.32).toLocaleString("en-UK"));
.as-console-wrapper { top: 0; max-height: 100%!important; }

Solution 3:

Expanding on the solution from @naitsirch we can use Intl.NumberFormat.formatToParts() to have JS parse the group and decimal separators.

functionparseLocaleNumber(stringNumber) {
  let num = 123456.789,
    fmt_local = newIntl.NumberFormat(),
    parts_local = fmt_local.formatToParts(num),
    group = '',
    decimal = '';

  parts_local.forEach(function(i) {
    switch (i.type) {
      case'group':
        group = i.value;
        break;
      case'decimal':
        decimal = i.value;
        break;
      default:
        break;
    }
  });

  returnparseFloat(stringNumber
    .replace(newRegExp('\\' + group, 'g'), '')
    .replace(newRegExp('\\' + decimal), '.')
  );
}

//replace this string with a number formatted for your localeconsole.log(parseLocaleNumber("987,654,321.01"));
//output for "en" locale: 987654321.01

Solution 4:

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

functionparseLocaleNumber(stringNumber, locale, currency_code) {
  let num = 123456.789,
    fmt_local = newIntl.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;
    }
  });

  returnparseFloat(stringNumber
    .replace(newRegExp('\\' + group, 'g'), '')
    .replace(newRegExp('\\' + decimal), '.')
    .replace(newRegExp('\\' + currency, 'g'), '')
  );
}

//replace inputs with a number formatted for your locale, your locale code, your currency codeconsole.log(parseLocaleNumber('$987,654,321.01', 'en', 'USD'));
//output for "en" locale and "USD" code: 987654321.01

Solution 5:

No, comma (,) is an operator having special meaning, just like dot (.). Otherwise things as simple as:

var array1 = [1,2];
var array2 = [1.2];

would break under different locales. All mainstream languages I know treat . and , separately and stricly, irrespective to locale.

Post a Comment for "Does Javascript Take Local Decimal Separators Into Account?"