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.mynum):
$('span.mynum').number( 2000.6156, 2 )
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:
// 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: