jQuery Number Plugin
Custom D 2015By Sam Sehnert,
This is a jQuery plugin which allows developers to easily format numbers for display use. Allows users to replace numbers inline in a document, or return a formatted number for other uses.
Requires jQuery 1.6 or greater.
See our jQuery Number Format article for more information.
Basic number formatting
The number method takes up to four parameters, but only the first one is required.
Number: The number you want to format.$; // Outputs 5,020
Decimal Places: The number of decimal places you wish to see. Defaults to 0.$; // Outputs: 5,020.24
Decimal Separator: The character(s) to use as a decimal separator. Defaults to '.'.$; // Outputs: 135,873
Thousands Separator: The character(s) to use as a thousands separator. Defaults to ','.$; // Outputs: 5 020,2
Number formatting as-you-type
When targeting a collection of input elements, you can have the number format plugin automatically format the users input based on your format settings.
true to the number parameter, indicates that you want the value of the field or element to be effected, instead
of placing the passed number into the field or element. All other parameters are as decribed above.
When the user types, their 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.
Automatic paste formatting is also supported.
Writing numbers into an element
; // Changes the text value of the element matching selector to the formatted number.
Formatting numbers within a collection of elements
Assuming we have the following structure:
// the 'true' signals we should read and replace the text contents of the target element.
And come away with this result: