今天我在分配负数和正数的问题上存在问题。例如,我有一个文本框来插入我的号码和写入数字后的结果。突然,数字用逗号分隔符分隔,如数字为正数或负数
eg : 1000 -> 1,000
-1000 -> -1,000
-1000.12 -> -1,000.12
-0.00001 -> -0.00001
如何使用javascript实现这一点,我所知道的是使用onkeypress和onkeyup。非常感谢你:)
答案 0 :(得分:1)
这不是最佳解决方案,但您可以根据需要实施此解决方案。
var msg = document.getElementById('myInputBox'),
numberPattern = /^[0-9]+$/;
msg.addEventListener('keyup', function(e) {
msg.value = getFormattedData(msg.value);
});
function checkNumeric(str) {
return str.replace(/\,/g, '');
}
Number.prototype.format = function() {
return this.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
};
function getFormattedData(num) {
var i = checkNumeric(num),
isNegative = checkNumeric(num) < 0,
val;
if (num.indexOf('.') > -1) {
return num;
}
else if (num[num.length - 1] === ',') {
return num;
}
else if(i.length < 3) {
return i;
}else {
val = Number(i.replace(/[^\d]+/g, ''));
}
return (isNegative ? '-' : '') + val.format();
}
&#13;
<input type="text" id='myInputBox' value="" />
&#13;