Reputation: 5890
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
Upvotes: 0
Views: 51
Reputation: 300
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)
.
Upvotes: 1