goog.i18n.NumberFormat: Formatting numbers to localized strings

By using Closure’s NumberFormat class (located under goog.i18n package) is relatively easy to format numbers and print readable strings. All we have to import is goog.i18n.NumberFormat:


Then, we have to create an instance of that class and specify the type of format to apply, by choosing among: CURRENCY, DECIMAL, SCIENTIFIC and PERCENT. Assuming we have to display a budget, we will write a similar statement:

// create a new formatter
var formatter = new goog.i18n.NumberFormat(goog.i18n.NumberFormat.Format.CURRENCY);

// test the output

The code above, by using the default locale, will print: $15,650.58. Is possible to localize the output by assigning a different symbols set to goog.i18n.NumberFormatSymbols. The code below will set an italian format:

// symbols setting
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_it_IT; 

// redefine formatter (in order to use new symbols set)
formatter = new goog.i18n.NumberFormat(goog.i18n.NumberFormat.Format.CURRENCY);

// see the differences

This time the output will be: € 15.650,58.