DEV Community

Cover image for JavaScript Interview Question #45: Сurrency formatting in JS
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com

17 3

JavaScript Interview Question #45: Сurrency formatting in JS

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' }));
Enter fullscreen mode Exit fullscreen mode

These numbers are formatted differently:

$99.00
49,00 €
₹19.00
Enter fullscreen mode Exit fullscreen mode

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.

Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay