-
Notifications
You must be signed in to change notification settings - Fork 1
/
numToWords.ts
55 lines (50 loc) · 1.07 KB
/
numToWords.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
export function numToWords(num: number): string {
const words = [
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
'eleven',
'twelve',
'thirteen',
'fourteen',
'fifteen',
'sixteen',
'seventeen',
'eighteen',
'nineteen',
];
const tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
if (num < 20) {
return words[num];
}
if (num < 100) {
const remainder = num % 10;
if (remainder === 0) {
return tens[Math.floor(num / 10) - 2];
}
return `${tens[Math.floor(num / 10) - 2]} ${words[remainder]}`;
}
if (num < 1000) {
const remainder = num % 100;
if (remainder === 0) {
return `${words[Math.floor(num / 100)]} hundred`;
}
return `${words[Math.floor(num / 100)]} hundred ${numToWords(remainder)}`;
}
if (num < 10_000) {
const remainder = num % 1000;
if (remainder === 0) {
return `${words[Math.floor(num / 1000)]} thousand`;
}
return `${words[Math.floor(num / 1000)]} thousand ${numToWords(remainder)}`;
}
throw new Error('Number too large');
}