php - How can I format currency by using JQuery -
this question has answer here:
- convert currency format 5 answers
i trying format currency using 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 work volume such "$10,000" or that, how can include thousands, hundreds, , millions in 1 code?
here nice function in vanilla js handles things:
var format = function(num){ var str = num.tostring().replace("$", ""), parts = false, output = [], = 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, jquery, turn plug-in, or use like:
$(function(){ $("#currency").keyup(function(e){ $(this).val(format($(this).val())); }); });
edit updated fiddle jsfiddle
Comments
Post a Comment