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:

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):

QuarterRevenue
Q145000000
Q237000000
Q368000000
Q489000000

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):

QuarterRevenue
Q145000000
Q237000000
Q368000000
Q489000000

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.