Saturday, April 20, 2024
HomeTechnologySoftwareHow to Internationalize Numbers with JavaScript

How to Internationalize Numbers with JavaScript

Date:

Related stories

Lando Norris takes F1 Chinese Grand Prix sprint pole from Hamilton

SHANGHAI — McLaren's Lando Norris had his fastest lap deleted...

Manchester Thunder 61-46 Severn Stars

Highlights of the Netball Super League match between...

Have a Lovely Weekend. | Cup of Jo

What are you up to this weekend? I’m...

Week 1 Meal Plan | The Recipe Critic

This website may contain affiliate links and advertising...
spot_imgspot_img

Presenting numbers in a readable format takes many forms, from visual charts to simply adding punctuation. Those punctuation, however, are different based on internationalization. Some countries use , for decimal, while others use .. Worried about having to code for all this madness? Don’t — JavaScript provides a method do the hard work for you!

The Number primitive has a toLocaleString method to do the basic formatting for you:

const price = 16601.91;

// Basic decimal format, no providing locale
// Uses locale provided by browser since none defined
price.toLocaleString(); // "16,601.91"

// Provide a specific locale
price.toLocaleString('de-DE'); // "16.601,91"

// Formatting currency is possible
price.toLocaleString('de-DE',  
  style: 'currency', 
  currency: 'EUR' 
); // "16.601,91 €"

// You can also use Intl.NumberFormat for formatting
new Intl.NumberFormat('en-US', 
  style: 'currency',
  currency: 'EUR'
).format(price); // £16,601.91

It’s a major relief that JavaScript provides us these type of helpers so that we don’t need to rely on bloated third-party libraries. No excuses — the tool is there!

  • CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point…

  • 5 HTML5 APIs You Didn’t Know Existed

    When you say or read “HTML5”, you half expect exotic dancers and unicorns to walk into the room to the tune of “I’m Sexy and I Know It.”  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature…



Source link

Latest stories

spot_img