Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format currency by using JQuery [duplicate]

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?

like image 939
Swanney_14 Avatar asked May 31 '14 03:05

Swanney_14


2 Answers

Here is a nice function in vanilla JS that handles things:

var format = function(num){
    var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null;
    if(str.indexOf(".") > 0) {
        parts = str.split(".");
        str = parts[0];
    }
    str = str.split("").reverse();
    for(var j = 0, len = str.length; j < len; j++) {
        if(str[j] != ",") {
            output.push(str[j]);
            if(i%3 == 0 && j < (len - 1)) {
                output.push(",");
            }
            i++;
        }
    }
    formatted = output.reverse().join("");
    return("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""));
};

However, for jQuery, you could always turn it into a plug-in, or just use it like:

$(function(){
    $("#currency").keyup(function(e){
        $(this).val(format($(this).val()));
    });
});

EDIT I updated the fiddle JSFiddle

like image 136
faino Avatar answered Sep 22 '22 02:09

faino


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:

$('input').on('input', function(e){    
  $(this).val(formatCurrency(this.value.replace(/[,$]/g,'')));
}).on('keypress',function(e){
  if(!$.isNumeric(String.fromCharCode(e.which))) e.preventDefault();
}).on('paste', function(e){    
  var cb = e.originalEvent.clipboardData || window.clipboardData;      
  if(!$.isNumeric(cb.getData('text'))) e.preventDefault();
});
function formatCurrency(number){
  var n = number.split('').reverse().join("");
  var n2 = n.replace(/\d\d\d(?!$)/g, "$&,");    
  return "$" + n2.split('').reverse().join('');
}

Demo.

like image 25
King King Avatar answered Sep 21 '22 02:09

King King