Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

Handling Currency in JavaScript

| Comments

Oh yeah! Handling currency got better with Intl object, which provides a namespace for the standard internationalization constructors.

Intl object has many intresting functions in it (as below) but in this write-up I’m looking at a specific functionality.

  • Collator : Constructor for collators, objects that enable language sensitive string comparison.

  • DateTimeFormat : Constructor for objects that enable language sensitive date and time formatting.

  • NumberFormat : Constructor for objects that enable language sensitive number formatting.

Simple code to format currency : (Tested in chrome canary and FF nightly)

1
2
3
4
5
6
7
8
var currency = function(type){
  return new Intl.NumberFormat([ "en-IN" ], {
    style: "currency",
    currency: type,
    currencyDisplay: "symbol",
    maxmimumFractionDigit: 1
  });
 };

Now let play around with currency ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
currency("INR").format(10023.56)
"Rs10,023.56"

currency("USD").format(10023.56)
"$10,023.56"

currency("GBP").format(10023.56)
"£10,023.56"

currency("YEN").format(10023.56)
"YEN10,023.56"

currency("CNY").format(10023.56)
"CN¥10,023.56"

P.S : Sticking with "en-IN" as the NumberFormat, it can be changed as per the need.

Hope there shall be a standard API for currency convertion! That would be very useful? :)

Comments