匹配input内只能输入数字和","逗号或者说是千分位符;
PS:使用千分位符时,一般只保留2位小数
如果没有特殊说明可以用html中的
<input type="number">
/*限制只能输入数字 和 "," */
if ($(this).val().length == 1) {
$(this).val($(this).val().replace(/[^1-9]/g, ''));
} else {
$(this).val($(this).val().replace(/\D,/g, ''));
}
数字装千分位格式,千分位格式转回数字格式
/*千分位转整数*/
function thousandsToNumber(str){
str = typeof(str) == "string" ? str : str.toString(); //将传入参数转为字符串以做修改
return parseFloat(str.split(",").join(""));
}
/*整数 小数 封装千分位符*/
function numberToThousands(number, n) {
number = thousandsToNumber(number.toString()); /*转为字符串*/
n = n == undefined || n == 0 ? 0 : n; //保留位数
var num = (Math.round(number * (Math.pow(10, n))) / (Math.pow(10, n))).toString(); //保留小数位数
var rs = num.indexOf('.'); //分离成小数部分和整数部分
/*对不足位数的补零*/
if (rs < 0) {
rs = num.length;
num += '.';
}
while (num.length <= rs + n) {
num += '0';
}
var integer = num.split(".")[0];
var decimal = num.split(".")[1];
/*保留小数 不保留小数*/
return n == 0 ? integer.toString().replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,') : integer.toString().replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,') + "." + decimal;
}
部分资源来源: http://blog.csdn.net/zyj_15067066062/article/details/72469735