Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Javascript Intl.NumberFormat

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>
like image 494
jbd Avatar asked Jan 29 '26 00:01

jbd


2 Answers

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));
like image 176
Nina Scholz Avatar answered Jan 30 '26 14:01

Nina Scholz


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);
like image 30
bthe0 Avatar answered Jan 30 '26 14:01

bthe0