Can someone please explain why the following code does not work unless I hard code the json? I would like to be able to swap various locale, currency values in.
<html>
<body>
<script>
currency = 'GBP';
locale = 'en-GB';
var json = `{ style: 'currency', currency: '${currency}', minimumFractionDigits: 0, maximumFractionDigits: 0 }`;
console.log(json);
cf = new Intl.NumberFormat(locale, json);
document.write(cf.format(1887732.233) + "<br>");
</script>
</body>
</html>
The problem is this part:
currency: '${currency}'
which is not a template literal, but just a string.
You need this instead:
currency: `${currency}`
or just
currency: currency
or even, which Mr. Spock in the comments mentioned, with a short hand property
currency
var currency = 'GBP',
locale = 'en-GB';
json = {
style: 'currency',
currency,
minimumFractionDigits: 0,
maximumFractionDigits: 0
};
console.log(json);
cf = new Intl.NumberFormat(locale, json);
console.log(cf.format(1887732.233));
Your code works just fine without json like this:
var config = { style: 'currency', currency: currency, minimumFractionDigits: 0, maximumFractionDigits: 0 };
cf = new Intl.NumberFormat(locale, config);
cf.format(123);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With