The following code is used for validating the numbers with digit grouping(ie. Convert the digits into like Currency $) using Javascript. For ex, 1. If you given the input 20000, it generates the output $20,000.00 2. If you given the input 2555, it generates the output $2,555.00 And also it is having some validation, whether if the input is number or not
function digitGrouping(digit) { var obj = document.getElementById(digit); var digit = document.getElementById(digit).value; var isGroup = "1234567890,.$"; var chk; for(var i = 0; i <= digit.length-1; i++) { if(isGroup.indexOf(digit.substring(i, i+1)) != -1) { chk = true; } else { chk = false; alert("Not a valid number \nNumber format should be like this 1,000,000.00"); return; } }
if(chk == true) { var newDigit = digit.split("."); var newDigit1 = newDigit[0]; var newDigit2 = newDigit.length > 1 ? '.' + newDigit[1] : '00'; var commas = /\,/g var isDigit = /^[1-9]/; var isDollor = /^\$/; if(isDigit.test(newDigit1) || isDollor.test(newDigit1)) { if(commas.test(newDigit1)) { newDigit1 = replaceCommas(newDigit1.replace(/\,/g, "")); newDigit1 = replaceCommas(newDigit1.replace(/\$/g, "")); } else { newDigit1 = replaceCommas(newDigit1); newDigit1 = replaceCommas(newDigit1.replace(/\$/g, "")); } if (newDigit[1]) { obj.value = "$" + newDigit1 + newDigit2; } else { obj.value = "$" + newDigit1 + "." + newDigit2; } } else { alert("Not a valid number, All number cannot be Zero \nNumber format should be like this 1,000,000.00"); } } else { alert("Not a valid number \nNumber format should be like this 1,000,000.00"); } }
function replaceCommas(digit) { var regExp = /(\d+)(\d{3})/; while(regExp.test(digit)) { digit= digit.replace(regExp, '$1' + ',' + '$2'); } return digit; }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|