简体   繁体   中英

javascript limit on positive and negative number with delimiter comma based onkeyup and onkeypress

Today i have problem in delimiting number for negative and positive number. For example, i have a textbox to insert my number and the result after write the number. Suddenly the number is separated with comma delimiter like this either the number is positive or negative

eg :  1000 -> 1,000
     -1000 -> -1,000
     -1000.12 -> -1,000.12
     -0.00001 -> -0.00001 

How to achieve this using javascript, what i know is using onkeypress and onkeyup. Thank you very much :)

This is not the best solution, but you can implement this according to your need.

 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(); } 
 <input type="text" id='myInputBox' value="" /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM