Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
how to separate numbers in javascript
const inpNumber = document.getElementById("my-decimal-number");
inpNumber.addEventListener("keyup", handlerSeparateNumbers)
// functions
function funcReverseString(str) {
return str.split('').reverse().join('');
}
// event handlers
function handlerSeparateNumbers(e) {
const thisElement = e.target;
let thisElementValue = thisElement.value;
thisElementValue = thisElementValue.replace(/,/g, "");
if (isNaN(Number(thisElementValue))) {
alert("لطفا از وارد کردن حروف خودداری فرمایید !")
return false;
}
let seperatedNumber = thisElementValue.toString();
seperatedNumber = funcReverseString(seperatedNumber);
seperatedNumber = seperatedNumber.split("");
let tmpSeperatedNumber = "";
j = 0;
for (let i = 0; i < seperatedNumber.length; i++) {
tmpSeperatedNumber += seperatedNumber[i];
j++;
if (j == 3) {
tmpSeperatedNumber += ",";
j = 0;
}
}
seperatedNumber = funcReverseString(tmpSeperatedNumber);
if(seperatedNumber[0] === ",") seperatedNumber = seperatedNumber.replace("," , "");
thisElement.value = seperatedNumber;
}
@senior-x-79

This comment has been minimized.

Copy link
Owner Author

@senior-x-79 senior-x-79 commented Aug 9, 2021

کد اسنیپت مربوط به این مقاله می باشد .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment