javascript interview question #45

How to format a string into a local currency in JavaScript? What’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In the first line we create a constant price of a type BigInt. This type is often used in finance as it can safely store numbers above the Number.MAX_SAFE_INTEGER.

Then, we try to format the number 99n into a local currency using the function toLocaleString.

To make sure the formatting goes well, we need to pass two arguments into toLocaleString:

  • locale, for example en-US, — defines the output format
  • object with the formatting options

One of the formatting options, could be style: 'currency'. If you specify this option, then the number will be formatted as a currency of a specific region:

console.log(99n.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));
console.log(49n.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
console.log(19n.toLocaleString('en-IN', { style: 'currency', currency: 'INR' }));

These numbers are formatted differently:

$99.00
49,00 €
₹19.00

But, if you look attentively into the original code snippet, you’ll notice, that the options don’t have the currency field. Without it, the formatting doesn’t make sense and won’t work.

The error will be thrown and the conversion from BigInt to a local currency string won’t happen.


ANSWER: An error TypeError: Currency code is required with currency style. will be logged to the console.