Skip to content

Instantly share code, notes, and snippets.

@Fanna1119
Created July 13, 2026 05:29
Show Gist options
  • Select an option

  • Save Fanna1119/529722c261f5bc76269f02f0869424d0 to your computer and use it in GitHub Desktop.

Select an option

Save Fanna1119/529722c261f5bc76269f02f0869424d0 to your computer and use it in GitHub Desktop.
Number to text
class NumberToWords {
private ones: string[] = [
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen'
];
private teens: string[] = this.ones.slice(10); // Reuse for teens
private tens: string[] = [
'', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'
];
private convertWithUnit(value: number, divisor: number, unit: string): string {
const quotient = Math.floor(value / divisor);
const remainder = value % divisor;
let result = this.convert(quotient) + ' ' + unit;
if (remainder > 0) {
result += ' ' + this.convert(remainder);
}
return result;
}
convert(value: number): string {
if (value === 0) return 'zero';
if (value < 0) return 'minus ' + this.convert(Math.abs(value));
switch (true) {
case value < 10:
return this.ones[value];
case value < 20:
return this.teens[value - 10];
case value < 100:
return this.tens[Math.floor(value / 10)] +
(value % 10 !== 0 ? ' ' + this.ones[value % 10] : '');
case value < 1e3:
return this.convertWithUnit(value, 100, 'hundred');
case value < 1e6:
return this.convertWithUnit(value, 1e3, 'thousand');
case value < 1e9:
return this.convertWithUnit(value, 1e6, 'million');
case value < 1e12:
return this.convertWithUnit(value, 1e9, 'billion');
default:
return this.convertWithUnit(value, 1e12, 'trillion');
}
}
convertCurrency(value: number): string {
const dollars = Math.floor(value);
const cents = Math.round((value - dollars) * 100);
let result = this.convert(dollars) + ' dollars';
if (cents > 0) {
result += ' and ' + this.convert(cents) + ' cents';
}
return result;
}
}
const converter = new NumberToWords();
console.log(converter.convert(1234)); // "one thousand two hundred thirty four"
console.log(converter.convert(1234567)); // "one million two hundred thirty four thousand five hundred sixty seven"
console.log(converter.convertCurrency(123.45)); // "one hundred twenty three dollars and forty five cents"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment