coder and technology lover
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:
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.
This entry was posted on 26, Thursday f, 2009 at 3:54 am, and is filed under google closure. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site.

