Follow us on Twitter

Web

jQuery Number Format: Redux

by Sam Sehnert

Download jQuery NumberAs-you-type Demo

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.

As-you-type!

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.

As-you-type Demo

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:

1025.8702
18023
982.3
.346323

We can then use this JavaScript:

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

1,025.87
18,023.00
982.30
0.35

Download jQuery NumberAs-you-type Demo

Comments

kreuk on 30 November, 2014

Last commit seems to have stuffed that useful piece of code ! your example jQuery.number( 135.8729, 3, ',' ) outputs 1,358,729,000

Sam Sehnert on 30 November, 2014

@kreuk - Oh no! Time to set up some unit tests I think... I've just committed a fix for that issue.

kreuk on 30 November, 2014

works like a charm now. Thank you !

Davis Tom on 28 February, 2014

thanks but in As-you-typewhen i typed letters also in the box, it's also taking as input. I need it to accept only numbers in and not letters, what to do?

Sam Sehnert on 01 March, 2014

@davis, Hey?good point. You can easily achieve that outside the .number plugin (although I agree, it should probably be a built in feature). Take a look at this Stack Overflow article for more info. Note that you can't use

 with the jQuery Number Format plugin, because we're use non-numeric characters for the thousands and decimal separators.

What you could do though, if you're keen on using an HTML5 feature, is use the input 'pattern' attribute.

Read more on Stack Overflow.

Davis Tom on 01 March, 2014

@Sam what about the first answer in here? can you implement it in jQuery? http://stackoverflow.com/questions/15131352/jquery-number-format-how-to-stop-letters-from-accepting

Sam Sehnert on 01 March, 2014

@davis, Nice, thanks for that. I've built it into the plugin now.

Davis Tom on 01 March, 2014

Thanks @Sam. appreciate it. :)

Davis Tom on 01 March, 2014

@Sam it's working fine in chrome, but not in firefox or IE.

Anonymous on 02 March, 2014

Hey great work on this plugin but the following example wont

$("#x").number(true)
will take the first char read and put it at the end of the string that is the user will input 2800 and the script will ouput in 8,002

Same anonymous on 02 March, 2014

The bug is in fact related to the cursor getting shifted back to its first position after the first key stroke. Also 2800 can produce 28 without letting 0 being accepted. I suspect the problem might be related to filtering or how you handle your cursor position. I'm not sure if keypad ids are the same as having numeric pads but I was using the keypad ids (numbers up the letters). It occured in Firefox + Safari. Anyways thanks for the work on this !

Davis on 04 March, 2014

@Sam now it's edited as working on chrome and FF can you add it to the jQuery? http://stackoverflow.com/questions/15131352/jquery-number-format-how-to-stop-letters-from-accepting/15131790#comment21416061_15131790

Sam Sehnert on 05 March, 2014

@davis, Fixed :-), thanks.

Davis on 05 March, 2014

@Sam Thanks :)

Russ on 07 March, 2014

FYI your As You Type Demo in Chrome will not work with the number pad, only with the keyboard numbers. Again in Chrome, pressing "." will not add the decimal point, you have to use the arrow keys. Sorry to say, I can't help with what the actual problem is. ;-)

Sam Sehnert on 07 March, 2014

@russ, this is due to this bug in Webkit: https://bugs.webkit.org/show_bug.cgi?id=99411 Numpad keys are reported as A ? I when using the new keyIdentifier property. I'll look at a workaround until that bug is fixed and included in Chrome. Incidentally, Chrome on OS X reports the correct characters.

Jernej on 18 March, 2014

Thank you for this wonderfull piece of code, i'm just having some problems entering numbers lower then 1, like 0.5 ... it just shows as 5.00 (chrome on windows, havent tried other browsers)

Sam Sehnert on 21 March, 2014

@jernej, Thanks for that. This issue has been reported by another user here: https://github.com/teamdf/jquery-number/issues/9.

Jason Harris on 04 April, 2014

Sam, can you email me ASAP. I'm trying to fix Issue #9 and I could use a quick run down of what each of the properties in the data object is used for (like data.c).

chag on 05 April, 2014

Hi, I'm trying to use your plugin in a form with 4 fields : - amount w/o taxes - vat rate - vat amount - total with vat. The 2 fields "vat rate" & "Total" can not be changed but "amount" and "vat amount" can. To calculate the vat rate, I have a "change" event on these two fields. but during my tests, I noticed that the eevnt is not always triggered. I made a test page here : http://jsfiddle.net/LHaqY/ If you try to change the value of the first field then fcusout (tab key or clicking anywhere else on the page, the change event should trigger. Sometimes it does. ometimes it doesn't.

Sam Sehnert on 07 April, 2014

@chag, yeah I've got a bug ticket open for this on GitHub. It's caused by an issue with jQuery's valHooks... basically, if a 'set' val-hook changes the length of the value in the field it won't fire the change event for its next run. If the set val-hook is run again, and it doesn't change the length of the value, then it does run the change event. It's a bit of a pain ? I haven't found a work-around for this yet, but I'm still looking into it.

Luis on 17 April, 2014

Hello, The script is very good! The only featured missed is the possibility to use negative numbers. Can we expect an update for this? Thank you in advance, Regards

Sam Sehnert on 17 April, 2014

@luis, Yeah, thats something I've been wanting to add, but I haven't had a need to yet. You're more than welcome to have a go, and submit a pull request on Github though?It might be a few months away if you wait for me to do it :-)

stix on 13 May, 2014

best number formater i found. but there is one issue, if i enter numbers to input via numpad, that's ok. but if i use shift + number key it not works. i try to change keydown event to keyup, this works but after enter first number, cursor is moved to start.

stix on 13 May, 2014

for issue I wrote in previous post, there you can find solution by me: https://github.com/teamdf/jquery-number/issues/17

Deepak on 25 May, 2014

I have a problem I binded an input by this code $('#price').number(true, 2); But when I type 0.23 that input behaves incorrectly..

sebastienC on 29 May, 2014

$.number(1999.955, 2, ',', ' ') => "1 999,96" changing the thousand to "." $.number(1999.955, 2, ',', '.') => "1.999.955,00" that's what it should do...

Harsh on 12 June, 2014

Hello, It doesn't allow the user to add the the value 0.01. When I type 1.00 the change it 0.01 then it works. Also it doesn't allow the user to add the decimal it make the number 0.00. please fix this. Thanks

Karl Gohery on 15 June, 2014

Hi Sam, great plugin, but a pretty major bug is that is doesn't allow you to enter decimals lower than 1 e.g. 0.25 or 0.83. I think this is the same issue Deepak and Harsh are having. Any plans to address this? Thanks!

Sam Sehnert on 15 June, 2014

@karl, Cheers ? yeah, I've got a few clients using this plugin now, and it's becoming a problem for them too. Unfortunately I've been tied up with other clients at present, but I do hope to fix this bug within the next two weeks.

need update on 03 July, 2014

Need an update on function to convert back to the real value. Yeah i know we just need to strip the thousands operator, but it would be neat if it is packaged in the function. like: $.number.convert_back('1,234.56'); //will result 1234,56 thanks.

Isaac Rivera on 04 July, 2014

Hey this plugin is fantastic. I second the request from @need. Parsing the value back would be nice:

$('span.mynum').number(false); // 2000.6156

plusagin on 16 July, 2014

dear Sam i have used this plug-in in asp.net c# with a normal page (aspx) it work perfectly. but if i use onto "user custom control (ascx) " page , at the first time page on initial it work fine (if value is 0 it converts to 0.0 itself ) after that if i change a value to others it does not work anymore . this is bug ? or i did something wrong ?

plusagin on 16 July, 2014

i got a solution , i have to put this js code in custom control Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded("function name") thanks

Niels on 17 July, 2014

Hi, great plugin! I'm wondering if it's possible to unbind the plugin on a certain field? Looking forward to your responds.

Özkan on 17 July, 2014

Hi, How can i get output like this ?? I need "," depens on "." 9,25 10,75 109,99 Thanks

Domingo Cortez on 23 July, 2014

Fantastic plugin, i'm waiting for the update for the 0.XXXX value.... nice work...Thanks you

Shashank verma on 26 July, 2014

Ha ha ha......... LOL Infact A BIG 0 !!!!!!!!!!!! to this boss........... We already have number_format command(function) in Php and likewise where the actual means and way of passing arguments is way similar to method in php.plz go to manual http://www.php.net/manual/en/function.number-format.php We are integrating same functionality here...so nothing so cool for me here.. :( :(

Sam Sehnert on 31 July, 2014

@shashank, Thanks for your input. If you read the original article then you'll realise that this plugin (for jQuery) was actually modelled on the PHP number_format function. Of particular note, the PHP number_format function is obviously a server side PHP function ? where-as this plugin provides the same functionality, using a comparable interface for JavaScript (A separate language from PHP). This plugin also provides as-you-type formatting, unlike it's PHP based counterpart.

shashank verma on 31 July, 2014

@Sam Sehnert .Hi dear,well we were not discussing for server side and client side string formatting.Yah,it sounds when we see plugin functionality as for client side format,but still i appreciate server side formatting's ,checks and validators.And for other purpose of formatting,we can have some 3-4 lines of our JQuery code for to do the same.No need of plugin Load here. :) :)

Michael Sobczak on 08 August, 2014

How do I suppress the comma separator for thousands? For example, I want 80000.00 and not 80,000.00

Sam Sehnert on 08 August, 2014

Hi Michael, The third and fourth parameters allow you to set the thousands and decimal characters (you can also set the thousands character to an empty string to hide it from the output). Check out the full documentation here: https://github.com/teamdf/jquery-number.

widjajayd on 12 August, 2014

Hi Sam, thank you for great plug ins I also patiently waiting for the update for the 0.XXXX value :-)

Sam Sehnert on 13 August, 2014

Hi All, I've just committed the update for the 'decimal's under 0' bug. You can get the latest version here: https://github.com/teamdf/jquery-number/releases

Brett Mallory on 14 August, 2014

Hi there. This is most helpful. Would it perhaps be possible to add a 'divisor' argument to the function so that we can divide the number. As in convert cents to dollars?

widjajayd on 14 August, 2014

Many Thanks Sam, Wow it very quick update I just download your update

AYColumbia on 16 August, 2014

Is this plug-in culture-aware? Other parts of the world use commas for the decimal/fractional part and the period for the thousands seperator and some use spaces. Same with the currency symbol and location of symbol, i.e., left side or right side.

Sam Sehnert on 16 August, 2014

@aycolumbia, It is insofar as it lets you change what the thousands separator and decimals are, and the number of decimal places. The logic of when to do that, is (presently) be up to you to decide. Number format doesn't allow currency symbols within the field?we usually do this by adding the currency format as a prefix or postfix element beside the field.

AYColumbia on 16 August, 2014

Thanks Sam. I realized this after I had posted it when I looked at the original article. It's a nice tool.

Bart A on 17 August, 2014

Hello Sam, Thanks for creating this nice plugin. I'm quite happy using it, as it does support key's as well. Thanks for that! I am just facing a difficulty using val() to 'empty' the fields where .number is applied to. When a .val = "" is done, the plugin automaticly enters a 0 in the field. Any way this can be disabled? In this fiddle: http://jsfiddle.net/4yjnj/3/ you can see what I mean. Thanks :) Keep up the good work! Bart

Andi Daniawan on 17 August, 2014

Hi Sam, Its a Great plugin! I love it so much. Thanks for your effort to publish it. Would be nicer if the

$(a).val(""); 
that doesn't clear the input's value but returns 0, could be disabled. Another thing, I got problem if I use digit format. The cursor always jumps to the after digit separator on the first key input. It makes me have to move the cursor left to do the next input. However, it still a great plugin. Andi

Sam Sehnert on 19 August, 2014

@andi, Your second issue has been fixed in the latest commit?please re-download. Also, if you could please create an issue in GitHub for the first one (.val), I'll take a look at it.

Logan L on 19 August, 2014

Great plugin, but how does one enter 50 cents? $('#price').number( true, 2 ); Typing in "0.50" turns into "50.00"

Logan L on 19 August, 2014

Oops - didn't notice that this was a known bug that was fixed in the last release. Is the demo page still using the older version? It's still showing the bug there.

Andi Daniawan on 20 August, 2014

Hi Sam, you really did great! I just tested it, and it works. Success...

alexis on 23 August, 2014

Hi, i got problem if the textbox is clear and press ".", it was not accepted. or clear field then input "0", then it displays "0.00", then press "." again, then it clears the field.

Peter G on 04 September, 2014

Nice piece of code! Very useful indeed. @Sashank: this code is for client-side formatting & validating user input as opposed to sending every keystroke back to the server. There is a place for php number_format and a place for jQuery number format. Nice to have a choice! (Actually I haven't got a choice: I have to process it client-side). So again, a big thankyou to Sam for taking the time and making the effort to come up with this plugin!

Aaron C on 22 September, 2014

I am using your plugin and it works pretty good for the most part. Sometimes wen I am in a field and I being to type a number the first number goes on to the left of decimal and the remaining input starts going to the right of the decimal. This doesn't always happen. I can provide a sample page if you need.

Danny on 02 November, 2014

Hi, how can i change the comma for dott, example i want 1200 as 1.200 not 1,200

Sam Sehnert on 04 November, 2014

@danny, The read me on GitHub explains this best: https://github.com/teamdf/jquery-number. Something like this: $.number( 5020.2364, 1, ',', ' ' ); // Outputs: 5 020,2

hotaru on 12 November, 2014

I have a problem as same as Aaron C. why when i type for second try, after first number then the cursor go to the end of the number??? and it's always happen. Please help.

Arda on 17 December, 2014

Hello, How can I use with dynamically added objects... Thank You

Sam Sehnert on 17 December, 2014

@Arda, you'll need to run the .number plugin after the object is added.

Arda on 18 December, 2014

Thank You :)

Maurizio A. on 03 January, 2014

I need to report a bug. When: I apply an AS-U-TYPE on a input type=text valorized *YET* (es. 10.200) What I do: $('.number').number( true, 3, ',', '.' ); Notice: decimal symbol, a comma thousan symbol, a full stop What I get: An input type valorized with string: 10.200,000 The value of element is (accessing by .val) 10200 This behavior is in disagreement with I think it must be. I'm expected an input type valorized with: 10,200 And this is the comportamet I find if: - apply the function $('.number').number( true, 3, ',', '.' ); on an EMPTY text - write on it with .val('10.200') - I get an input type valorized with 10,200 - The value (with val funcion) is 10.200 Thanks

Daniel Schmidt on 09 January, 2014

It's a great plugin. The only problem I have is when pressing the DEL key. For some reason I can only delete with backspace. Do you know why? Kind regards

Jess on 25 January, 2014

In input texts with v2.1.3 moves the cursor to the beginning of the line if you highlight the number and start typing a new number.. so typing "1200" ends up as "2100". This doesn't seem to happen in the demo (using v2.1.0). Also I cannot use delete, only backspace -- jquery 1.10.2. Thank you for a useful plugin!

Marco on 28 January, 2014

CONGRATULATIONS and THANK YOU for this library!! :-D But I must say I have the same problem Jess: " In input texts with v2.1.3 moves the cursor to the beginning of the line if you highlight the number and start typing a new number.. so typing "1200" ends up as "2100". This doesn't seem to happen in the demo (using v2.1.0). " I'm not able to solve this problem, I could get some help?

Devrim on 31 January, 2014

Hello Sam, Thanks for your plugin. I am using it every project. But I have a problem for using multiple array fields. I have same #id of multiple price input fields. For example when I type a number to first input everything ok. but second input doesn't work correctly. How to use your plugin multiple array fields? Thanks a lot Cheers

Sam Sehnert on 31 January, 2014

Hi @Devrim ? I'm not 100% sure what the issue is here, do you think you could post a bug report on Git Hub with an example page which demonstrates your problem? Are you using multiple ID's as in:






// And then in your JS.
$('#number').number(true,2);

// This won't work, because ID must be unique across an HTML document.
OR





// And then in your JS.
$('#number_1, #number_2, #number_3').number(true,2);

// This SHOULD work (if it doesn't its a bug).
I regularly use the plugin on multiple fields, but I tend to use something like this:
/**
 * Apply the as-you-type number formatter.
 */
$('input[data-number]').each(function(){
    var $this = $(this);
    $this.number(true,$this.data('decimals'));
});

Harlan Lewis on 05 February, 2014

Regarding issues with setting an empty input with $('input').val(''): in v2.1.3, this can be fixed by allowing type conversion when checking for empty content. On line 635, change:

if(val === '')
to:
if(val == '')
https://github.com/teamdf/jquery-number/issues/27

Nick on 29 April, 2014

Great plugin. The only thing I am having a problem when my input has a value from the start ex:



When i want to change the value in my input it will only let me use a number of one decimal ex:(3.33).

Thanks!

L. Phat Tai on 08 May, 2014

Do you have option to rebind format when working with Knockout?

Paullyie on 16 May, 2014

Great plugin, thanks a million Sam, Tried for a while to get ajax working but was not flexible enough and this plugin works great $(function () { $('#txtbox1').number(true, 4); }); I have one quick question wondering if this is possible: At the moment if you type a value it automatically populates the decimal and trailing zeros Would it be possible to not auto-populate the zeros? but still retain the mask of the number of decimal places? Hoping this is not a big change, Thanks

Commenter on 16 May, 2014

How does one unsubscribe from email updates on this thread? I'd hate to have to flag it as spam...

TheSnake on 23 May, 2014

There's an error if you copy an empty number field with clone() method, because the new element always contains 0 but it should be empty. I tried to remove the event with off() but it still puts a zero in there. Is there a workaround?

Thinh Nguyen on 18 June, 2014

Hello, I am trying to implement this plugin to my form, and there are some problems here: - I load a field with the default value = "0". When I click (focus) on that field, if the pointer is in font of the "0", everything works fine. But if the pointer is after the "0", when I type a number (e.g 3), the "0" is removed, also the pointer moves backward, appears in front of my number 3. This time I have to click on the field again to type the next number after "3". - I'm thinking of a solution, when I focus on the field, if its value is 0, auto clear it so that I can fill any number I want. But this has conflicted with the plugin, it doesn't allow me to do so.

Jeff Kee on 24 July, 2014

Great plugin guys. On a totally separate note.. the latest comment up there by Kreuk is timestamped November 2014.. and it's only July 2014! I was confused for a bit while looking at the progress logs, for a second doubting myself on what year I am in! Screenshot: http://imgur.com/x94jJ5b

Scott Howser on 29 July, 2014

When a page comes up with a default value of 25,000.00 and I select the entire value and start typing it will only allow me to type a few characters then it will stop. Once I delete the entrie contents it will work as expected. This is my call. $('input.cash').number(true, 2);

LongLH on 14 August, 2014

Hi Sam Sehnert, I have a issue. When I input "6000", it has formatted to "6,000". But when I want to change it to "5000", I delete digit "6" to input digit "5", but now, the value reset "0". Can you help me fix it ? Thanks Sam.

Dave on 27 August, 2014

Hi Sam I think this is in relation to an earlier comment, but I have noticed issues when trying to bind the format to a change event. In firefox it works perfectly, but for Safari, Chrome & IE it only works if the length of the field you are changing is exactly the same as the original length, otherwise the change doesn't trigger. I also noticed a similar issue on the github issues, but just wondered if there had been updates on this issue, or whether you would know why it works with firefox but not the others? Thanks

Sam Sehnert on 27 August, 2014

@dave, This is a known bug with jQuery valHooks. Basically, the valHook system prevents change events from being fired, and is a little too greedy in some cases — I've added more info here into the way forward: https://github.com/teamdf/jquery-number/issues/10

osvaldo on 13 September, 2014

Hi Thanks for your code, it's very useful for us. But I'm having trouble with an issue. I'm from spainiard speaking country, where currency gets formated diferently. E.G MXN $ 1.000,25 CLP $1.000.000 The first case means "A thousand Mexican Pesos and twenty five cents", the second case is "A million Chilean Pesos". As you can see, our currency format difers on dots (.) and colon (,) usage. I was looking into your code to see where I can change default currency format but I got kinda lost jajaja. Can you give me some advice, if I can make your formats more general I'll let you know ( And give code back of course [:blink] )

Ivan on 15 October, 2014

Hi, thanks for the examples, are very usefulls, but i have a problem. I have a input type=text with a onKeyUp event and when executes this the number event doen't work properly. I need help please!!!

Sam Sehnert on 15 October, 2014

@ivan, Could you please log a request on github, and post a link to example code for this issue?

Sam Sehnert on 15 October, 2014

@osvaldo, you can change the currency format by providing the characters you'd like to use as separators in the parameters... E.g., $('input.number').number(true,2,',','.'). Without providing the last two parameters, the decimal will default to a '.' and the thousand separator will default to a ','.

raja on 15 October, 2014

Thank you,It is working fine......

Jenny on 24 October, 2014

At some point I would like to reset my form so I do a

$("myForm input").val("")
Most of the form fields are empty, but those set to
.number( true, 2)
shows 0.00 instead of the placeholder that's supposed to be there (I set the placeholder after setting the values to empty string).

Something to say?

Digital Fusion is based in New

Some HTML is OK
  • <b>bold</b>
  • <i>italic</i>
  • <blockquote>
    blockquote
    </blockquote>
  • <pre>
    preformatted code
    </pre>