Last active
April 15, 2024 13:49
-
-
Save k-msalehi/9b2579d1dad5f0d79c6bb320a48a9cf7 to your computer and use it in GitHub Desktop.
convert english numbers to persian with thousand seperator (without tolocalstring)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function numberToPersian(number) { | |
let numberToString = number.toString(); | |
let result = ""; | |
const farsiDigits = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"]; | |
if (numberToString.length >= 4) { | |
let toPersian = numberToString | |
.split("") | |
.map((x) => farsiDigits[x]) | |
.join(""); | |
let persianSplit = toPersian.split(""); | |
let firstPersianPart = persianSplit.length % 3; | |
let noSecondPersianPart = Math.floor(persianSplit.length / 3); | |
if (firstPersianPart != 0) { | |
result = `${persianSplit.slice(0, firstPersianPart).join("")},`; | |
} | |
let secondPersianPart = persianSplit.slice(firstPersianPart); | |
for (let i = 0; i < secondPersianPart.length; i = i + 3) { | |
if (noSecondPersianPart <= 1) { | |
result += `${secondPersianPart.slice(i).join("")}`; | |
break; | |
} | |
result += `${secondPersianPart.slice(i, i + 3).join("")},`; | |
noSecondPersianPart = noSecondPersianPart - 1; | |
} | |
return result; | |
} else { | |
result = numberToString | |
.split("") | |
.map((x) => farsiDigits[x]) | |
.join(""); | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment