jQuery Number Format: Redux
A comment by 'awake' on my previous jQuery Number Format article has prompted me to rewrite this plugin to support returning the formatted number, while retaining the original .text()-like functionality.
And now, as-you-type automatic formatting of numbers in input elements!
Here's the original number formatting method, where the plugin will insert a the nicely formatted number into the target element (in this case, span.number):
$('span.number').number( 2000.6156, 2 )
The span.number element ends up looking like this:
You can also achieve international formats, by using the third and fourth parameters to set decimal and thousands separators respectively. This technique will work with all methods described below, including as-you-type.
$('span.number').number( 2000.6156, 3, ',', '.' )
In this case, the span.number element looks like this:
In with the new...
You can now have the plugin return the formatted number, like so:
$.number( 5100, 2 )
This new feature could be useful if you need to send a formatted number in a URL, as part of an AJAX request, or if you wanted to use the result in a loop.
If you apply the plugin to an input element (or a collection of them) the users input will automatically be converted in the correct format. This also attaches .val() hooks which allow you to continue using .val() to set your input elements, and you don't need to worry about handling the formatting.
It even seamlessly supports automatic formatting of numbers when pasted into the field.
Formatting numbers in bulk
There's another new feature: you can have the plugin iterate over a collection of elements, reading the number in each element, and replacing it with a formatted number.
Lets assume we have the following HTML:
<span class="number">1025.8702</span> <span class="number">18023</span> <span class="number">982.3</span> <span class="number">.346323</span>
// the 'true' signals we should read and replace the text contents of the target element. $('span.number').number( true, 2 )
Which would format the numbers in each target element, after which, the document would look like this:
<span class="number">1,025.87</span> <span class="number">18,023.00</span> <span class="number">982.30</span> <span class="number">0.35</span>