Skip to content

Instantly share code, notes, and snippets.

@shubhamkhuva
Last active September 29, 2023 08:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shubhamkhuva/b8332d864eea9737da842aa98be5a782 to your computer and use it in GitHub Desktop.
Save shubhamkhuva/b8332d864eea9737da842aa98be5a782 to your computer and use it in GitHub Desktop.
This code snippet provides a utility for converting numerical values into their textual representation in the Indian number format, commonly used for currency amounts.
export const getNumbersToWord = (numbers: any) => {
// stores word representation of given number n
let inWords = '';
// handles digits at ten millions and hundred
// millions places (if any)
inWords += getTranslatedNumber(Math.floor(numbers / 10000000), 'Crore ');
// handles digits at hundred thousands and one
// millions places (if any)
inWords += getTranslatedNumber(Math.floor(numbers / 100000) % 100, 'Lakh ');
// handles digits at thousands and tens thousands
// places (if any)
inWords += getTranslatedNumber(
Math.floor((numbers / 1000) % 100),
'Thousand ',
);
// handles digit at hundreds places (if any)
inWords += getTranslatedNumber(Math.floor((numbers / 100) % 10), 'Hundred ');
if (numbers > 100 && numbers % 100 > 0) {
inWords += 'and ';
}
// handles digits at ones and tens places (if any)
inWords += getTranslatedNumber(Math.floor(numbers % 100), '');
return inWords;
};
export const getTranslatedNumber = (numbers: any, s: string): any => {
let inWords = '';
const one = [
'',
'One ',
'Two ',
'Three ',
'Four ',
'Five ',
'Six ',
'Seven ',
'Eight ',
'Nine ',
'Ten ',
'Eleven ',
'Twelve ',
'Thirteen ',
'Fourteen ',
'Fifteen ',
'Sixteen ',
'Seventeen ',
'Eighteen ',
'Nineteen ',
];
const ten = [
'',
'',
'Twenty ',
'Thirty ',
'Forty ',
'Fifty ',
'Sixty ',
'Seventy ',
'Eighty ',
'Ninety ',
];
// if n is more than 19, divide it
if (numbers > 19) {
inWords += ten[numbers / 10] + one[numbers % 10];
} else {
inWords += one[numbers];
}
// if n is non-zero
if (numbers != 0) {
inWords += s;
}
return inWords;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment