It's #FrontendFriday

It's #FrontendFriday - JS Integrated NumberFormatter

Have you already faced the challenge of formatting and internationalizing numbers in JavaScript? Some of you will agree with me now. This is not a rewarding task, but it has become an important one. Today's users expect meaningful numbers, especially in the eCommerce sector. An integrated JavaScript API, the so-called Intl.NumberFormat, provides a remedy here.

According to the specification description, the object enables the language-dependent formatting of numbers and is therefore exactly the right tool to solve the problems mentioned above. Again, without adding another library. The constructor consists of two arguments. The first represents one or more locale strings and is based on the Best Current Practice 47. The second argument accepts a configuration object with the following options:

    • "localeMatcher" - Specifies the algorithm to be used for area pubic matching.

 

    • "style" - This option specifies the formatting style to be used. Possible values are "decimal", "currency", "percent" and "unit".

 

    • "currency" - Is intended for currency formatting in accordance with ISO 4217. If the "currency" option has been configured in the "style" property.

 

    • "unit" - Enables the exact specification of the "style" property. If "unit" is selected, the unit "kilometer-per-hour" can also be entered, for example.

 

    • "minimumIntegerDigits" - Specifies the minimum number of integer digits to be used.

 

    • "minimumFractionDigits" - Is the minimum number of fractional digits to be used.

 

    • "minimumSignificantDigits" - Is the minimum number of significant digits to be used.

 

Incidentally, it is also possible to specify maximum values for the digits group. The object created by the constructor has a format method that accepts a number to be formatted. The following is an example:
Example of JavaScript NumberFormatter

 

The times when you had to write your own formatter are over. Use the superpower of the browser! For those of you who are still struggling with IE support. Polyfills exist.

 

Learn more about Java programming

Sources:
W3C
gitconnected

Dennis Stricker

About ME

Stricker Dennis works as a passionate developer at the company doubleSlash in Friedrichshafen on Lake Constance. He completed his Master of Science degree at the Ravensburg-Weingarten University of Applied Sciences. His areas of specialization include the development and conception of modern Web applications and mobile apps in the B2B environment.

All contributions from Dennis Stricker

Learn more

Further information on our website and in our newsletter

Arrow up