0

I'm trying to understand a rounding function I found in inherited JavaScript code:

function percentageWithCommas(x?) {
    try {
        return (x * 100).toLocaleString("en-UK", { 
          maximumFractionDigits: 1, minimumFractionDigits: 1 }) + '%';
    } catch (e) {
        return (x * 100).toFixed(2) + '%';
    }
}

I understand that rounding in JS is nowadays done with .toLocaleString(...) rather than .toFixed().

Why would one implement the same thing in both the try and the catch phrase?

Reference

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
B--rian
  • 5,578
  • 10
  • 38
  • 89
  • 2
    It's probably a way to deal with `.toLocaleString` being unavailable, as in older browsers. (I don't think it's the best way to test for that.) – Pointy Jan 21 '20 at 14:56
  • UK, decimals are `.`,. also the catch uses 2 decimal places were as the locale uses 1.. so seems wrong anyway. – Keith Jan 21 '20 at 14:59
  • 1
    Explicitly check for the function: `if ((0).toLocaleString)` or something like that. – Pointy Jan 21 '20 at 15:11
  • Dear down-/close-voter(s), I understand that my question is not too advanced, but was that your reason to vote like you did? – B--rian Jan 21 '20 at 15:16
  • 1
    @B--rian For Javascript `(x?)` is an error, but maybe the OP is using Typescript, and hasn't put the typescript tag. Seems odd for it to be optional anyway, and if using Typescript would seem more appropriate to put `(x: number)`.. Or maybe the OP is using Flow, as that's similiar.. – Keith Jan 21 '20 at 16:01
  • Yeah, we are indeed using typescript. I written about ReactJS previously, but that was removed. – B--rian Jan 21 '20 at 16:13

1 Answers1

1

A double implementation seems to be useless: toLocaleString() has a high compatibility with old browsers, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Different issue: You should not use (x?) because if x is optional, you will have a problem with a null * 100. You better test if x is a number and do:

function percentageWithCommas(x) {
    if(isNaN(x)) return '';
    return (x * 100).toLocaleString("en-UK", { 
      maximumFractionDigits: 1, minimumFractionDigits: 1 }) + '%';
}

or something like that.

Note: In case you are worried that .toLocalString is not available, you can explicitly check for its existence with if ((0).toLocaleString).

B--rian
  • 5,578
  • 10
  • 38
  • 89
Tralgar
  • 240
  • 4
  • 14