I am trying to format currency by using this code below:
$('#currency').keyup(function(e){
var val = $(this).val();
val = val.replace(/[^0-9]/g,'');
if(val.length >= 2)
val = '$' + val.substring(0,2) + ',' + val.substring(2);
if(val.length >= 6)
val = val.substring(0,7) + val.substring(7);
if(val.length > 7)
val = val.substring(0,7);
$(this).val(val);
});
But that would work only for volume such as "$10,000" or something like that, How can I include thousands, hundreds, and millions in one code?
Here is a nice function in vanilla JS that handles things:
However, for jQuery, you could always turn it into a plug-in, or just use it like:
EDIT I updated the fiddle JSFiddle
Here is an example using jquery plugin:
Please refer :
https://code.google.com/p/jquery-formatcurrency/
Demo fiddle: jsfiddle.net/2wEe6/72
You can use
regex
in solving this problem, note that your input field should prevent user from typing letter/non-digit character, other than replacing all the typed non-digit characters with empty string, doing that is not professional:Demo.