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>
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>
Share
Improve this question
asked Apr 29, 2018 at 21:11
jbdjbd
1431 silver badge9 bronze badges
6
- 1 It's unclear what you mean by "unless I hardcode the json"? What are you trying to do? – nanobar Commented Apr 29, 2018 at 21:12
- Your "json" is an object literal, "en-GB" isn't a locale, it's a language code. The Intl object accepts an options object whose properties and names are used as values for the generated string. Are you really asking how to generate that object using variables? – RobG Commented Apr 29, 2018 at 21:15
- By hardcode the json, I mean repeat the json with all literals for each language. I would rather use a variable in that json parameter rather than duplicating it 50 times. – jbd Commented Apr 29, 2018 at 21:15
- Yes, I would like to avoid creating 50 different versions of that json for each language code. I would like to plug in a variable into that json – jbd Commented Apr 29, 2018 at 21:19
- @RobG, The reason I said locale is I saw this documentation new Intl.NumberFormat([locales[, options]]) at developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – jbd Commented Apr 29, 2018 at 21:22
2 Answers
Reset to default 4The 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 ments 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);