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:
1 2 3 | <script type="text/javascript"> goog.require("goog.i18n.NumberFormat"); </script> |
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:
1 2 3 4 5 | // create a new formatter var formatter = new goog.i18n.NumberFormat(goog.i18n.NumberFormat.Format.CURRENCY); // test the output console.log(formatter.format(15650.579)); |
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:
1 2 3 4 5 6 7 8 | // 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 console.log(formatter.format(15650.579)); |
This time the output will be: € 15.650,58.

