JsWorld
Tips and Tricks
1. Automatic formatting
To automate formatting of numeric, monetary and date/time data in your HTML you can devise a simple routine that selects the applicable elements and then applies JsWorld localisation to their content.
Here is an example how to automatically format all currency amounts in a page:
- When generating the markup give each HTML element that
contains a monetary value a special class, e.g.
"money"
. - When the page is loaded create a new JsWorld formatter for your chosen locale.
- Pull all elements of the
"money"
class. - Apply monetary formatting to each element.
Here a table which is formatted using the above technique. Each
td
element containing a quarterly revenue is given a
class "money"
.
<td class="money">45000000</td>
The original table (without applied formatting):
Quarter | Revenue |
---|---|
Q1 | 45000000 |
Q2 | 37000000 |
Q3 | 68000000 |
Q4 | 89000000 |
We then create a JsWorld monetary formatter for the en_US
locale. Using the jQuery library we pull all matching elements by their
class and then format them.
The result (note that this is a live demo):
Quarter | Revenue |
---|---|
Q1 | 45000000 |
Q2 | 37000000 |
Q3 | 68000000 |
Q4 | 89000000 |
Here is the complete JavaScript (jQuery required):
// Create new formatter for the chosen locale try { var mf = new jsworld.MonetaryFormatter(new jsworld.Locale(POSIX_LC.en_US)); } catch(error) { alert("Failed to create new monetary formatter: " + error); } // Pull all money elements $(".money").each(function(index) { try { // Get the value and apply formatting var formattedAmount = mf.format($(this).text()); // Update the number $(this).text(formattedAmount); } catch(error) { // Ignore errors } });
You can do the same with regular numbers, times, dates, etc.
2. Character encoding issues
Do you see garbled output in the browser? Most probably the cause is character encoding.
- The strings in the locale data files are stored in UTF-8 format. Make sure your web page is served with the same encoding.
- If you create your own locale definitions make sure that all characters outside the ASCII range are saved as a Unicode escape sequence (for example, specify the pound sign as "\u00a3" instead of "₤").
- If you still see strange output, they your OS probably lacks the appropriate font to display the required symbols.