input 输入框输入的数字转换成金额格式:
/* * caculate * input: 100000 * output: 100,000 */ (function ($) { var $input = $("#cacu-input"), $btn = $("#cacu-btn"), $result = $("#cacu-result"), result = 0, // 只允许数字及后退 filterNum = function (e) { // 数字和后退键以外禁用 if ((e.keyCode < 48 || e.keyCode > 57) && e.keyCode !== 8) { e.preventDefault(); return false; } }, // 格式化金额 formatCurrency = function (num) { num = num.toString().replace(/\$|\,/g, ''); if (isNaN(num)) { num = "0"; } var sign, cents; // 正负 小数 sign = ((Number(num) >= 0) ? '' : '-'); // 正负 num = Math.abs(num*100 + 0.50000000001); cents = num%100; num = Math.floor(num/100).toString(); if (cents < 10) { cents = '0' + cents; } for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) { num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3)); } return (sign + num); // + '.' + cents; }, getCurrency = function (num) { return num.replace(/\$|\,/g, ''); }; $input.on("keypress", function (e) { filterNum(e); }).on("keyup", function (e) { var val = $(this).val(); val = formatCurrency(val); $(this).val(val); }); $btn.on("click", function (e) { e.preventDefault(); var money = $input.val(); money = getCurrency(money); result = parseInt(money/500, 10); $result.text(result); }); })(window.jQuery);