Created
September 18, 2022 10:16
-
-
Save arafathusayn/082bf05d0d234b9f223241961f3a0685 to your computer and use it in GitHub Desktop.
Amount in Words (Lakh-Crore system) in TypeScript
This file contains 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
const a = [ | |
"", | |
"one ", | |
"two ", | |
"three ", | |
"four ", | |
"five ", | |
"six ", | |
"seven ", | |
"eight ", | |
"nine ", | |
"ten ", | |
"eleven ", | |
"twelve ", | |
"thirteen ", | |
"fourteen ", | |
"fifteen ", | |
"sixteen ", | |
"seventeen ", | |
"eighteen ", | |
"nineteen ", | |
]; | |
const b = [ | |
"", | |
"", | |
"twenty", | |
"thirty", | |
"forty", | |
"fifty", | |
"sixty", | |
"seventy", | |
"eighty", | |
"ninety", | |
]; | |
const regex = /^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/; | |
const getLT20 = (n: string) => a[Number(n)]; | |
const getGT20 = (n: string) => b[n[0]] + " " + a[n[1]]; | |
function numWords(input: string): string { | |
const num = Number(input); | |
if (isNaN(num)) return ""; | |
if (num === 0) return "zero"; | |
const numStr = num.toString(); | |
const matched = `000000000${numStr}`.slice(-9).match(regex); | |
if (!matched) { | |
return ""; | |
} | |
if (numStr.length > 9) { | |
return ( | |
numWords(numStr.slice(0, numStr.length - 7)) + | |
" crore " + | |
numWords(numStr.slice(-7)) | |
); | |
} | |
const [, n1, n2, n3, n4, n5] = matched; | |
let str = ""; | |
str += parseInt(n1) !== 0 ? (getLT20(n1) || getGT20(n1)) + "crore " : ""; | |
str += parseInt(n2) !== 0 ? (getLT20(n2) || getGT20(n2)) + "lakh " : ""; | |
str += parseInt(n3) !== 0 ? (getLT20(n3) || getGT20(n3)) + "thousand " : ""; | |
str += parseInt(n4) !== 0 ? getLT20(n4) + "hundred " : ""; | |
str += parseInt(n5) !== 0 && str !== "" ? "and " : ""; | |
str += parseInt(n5) !== 0 ? getLT20(n5) || getGT20(n5) : ""; | |
return str.trim(); | |
} | |
// console.log(numWords("19231391230123")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment