neil
neil

Reputation: 1306

Testing for toLocaleString support

I use toLocaleString to format a British job salary, passing in options for currency like this:

tempSalary = parseInt(salary).toLocaleString('en-gb', { style: 'currency', currency: 'GBP'});

I know that this doesn't get implemented properly in Safari, but could I check in advance to output something else? As per the MDN description, could I check for locales and options arguments, and if unsupported, don't bother with the script?

I'd rather check for support than just check whether using Safari (as IE10- also doesn't support it fully).

Upvotes: 0

Views: 2396

Answers (2)

RobG
RobG

Reputation: 147523

ECMA-402 says that to support options for Number.prototype.toString, an implementation must:

  1. Be consistent with ECMAScript Ed 5.1 and its successors
  2. Extend the built–in Number.prototype
  3. Implement an Intl global object
  4. Support the Intl.NumberFormat constructor

So based on that, a test for support is:

if (typeof Intl == 'object' && typeof Intl.NumberFormat == 'function') {

  // toLocaleString with options supported

} else {

  // host dependent

}

As a function:

function toLocaleStringSupportsOptions() {
  return !!(typeof Intl == 'object' && Intl && typeof Intl.NumberFormat == 'function');
}

It must be tested widely of course. It works in the few more popular browsers I tested, some with and some without Intl.NumberFormat support.

However there may be bugs within implementations. The only one I can think of that might occur is that some may not return expected values for typeof, even though they are required to (e.g. in the past there have been browsers that return 'unknown' instead of 'object' or 'object' instead of 'function'). Also, ECMA-262 ed 3 implementations are not required to throw an error if an options parameter is provided, so detection based on try..catch may fail in those hosts.

The following is a more tolerant version (but I would use the above until I discovered a host where it's required):

function toLocaleStringSupportsOptions() {
  return !!(typeof Intl != 'undefined' && Intl && typeof Intl.NumberFormat != 'undefined');
}

Upvotes: 8

LcKjus
LcKjus

Reputation: 141

Maybe you can make a function as MDN suggests. And handle the error accordingly.

function toLocaleStringSupportsLocales() {
  var number = 0;
  try {
    number.toLocaleString('i');
  } catch (e) {
    return e​.name === 'RangeError';
  }
  return false;
}

Upvotes: 1

Related Questions