Created
October 16, 2023 10:21
-
-
Save Shibily-kms/e0ec7f2fe0534aedb5f3b22ec6887575 to your computer and use it in GitHub Desktop.
Amount write in word
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 numberInWord = (amount) => { | |
const units = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']; | |
const teens = ['', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']; | |
const tens = ['', 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']; | |
const thousands = ['', 'Thousand', 'Million', 'Billion', 'Trillion']; // Extend as needed | |
function convertThreeDigits(num) { | |
const numStr = num.toString(); | |
const [a, b, c] = numStr.padStart(3, '0').split('').map(Number); | |
let result = ''; | |
if (a > 0) { | |
result += units[a] + ' Hundred '; | |
} | |
if (b === 1) { | |
result += teens[c] + ' '; | |
} else { | |
result += tens[b] + ' ' + units[c] + ' '; | |
} | |
return result; | |
} | |
function convertToWords(amount) { | |
if (amount === 0) { | |
return 'Zero'; | |
} | |
const amountStr = amount.toString(); | |
const chunks = []; | |
for (let i = amountStr.length; i > 0; i -= 3) { | |
chunks.push(amountStr.slice(Math.max(0, i - 3), i)); | |
} | |
let words = ''; | |
for (let i = chunks.length - 1; i >= 0; i--) { | |
const chunk = parseInt(chunks[i]); | |
if (chunk === 0) continue; | |
words += convertThreeDigits(chunk) + thousands[i] + ' '; | |
} | |
return words.trim(); | |
} | |
return convertToWords(amount); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment