Convert an integer to its English word representation. Examples: 1200 → "twelve hundred" 1000 → "one thousand" 1_000_000 → "one million" -42 → "negative forty-two" 0 → "zero"
(n: int)
| 61 | |
| 62 | |
| 63 | def number_to_words(n: int) -> str: |
| 64 | """ |
| 65 | Convert an integer to its English word representation. |
| 66 | |
| 67 | Examples: |
| 68 | 1200 → "twelve hundred" |
| 69 | 1000 → "one thousand" |
| 70 | 1_000_000 → "one million" |
| 71 | -42 → "negative forty-two" |
| 72 | 0 → "zero" |
| 73 | """ |
| 74 | if not isinstance(n, int): |
| 75 | n = int(n) |
| 76 | if n == 0: |
| 77 | return "zero" |
| 78 | if n < 0: |
| 79 | return f"negative {number_to_words(-n)}" |
| 80 | |
| 81 | # X00–X999 read as "X hundred" (e.g. 1200 → "twelve hundred") |
| 82 | # Exclude exact multiples of 1000 (1000 → "one thousand", not "ten hundred") |
| 83 | if 100 <= n <= 9999 and n % 100 == 0 and n % 1000 != 0: |
| 84 | hundreds = n // 100 |
| 85 | if hundreds < 20: |
| 86 | return f"{_ONES[hundreds]} hundred" |
| 87 | |
| 88 | parts = [] |
| 89 | for i, scale in enumerate(_SCALE): |
| 90 | chunk = n % 1000 |
| 91 | if chunk: |
| 92 | chunk_words = _three_digits_to_words(chunk) |
| 93 | parts.append(f"{chunk_words} {scale}".strip() if scale else chunk_words) |
| 94 | n //= 1000 |
| 95 | if n == 0: |
| 96 | break |
| 97 | |
| 98 | return " ".join(reversed(parts)) |
| 99 | |
| 100 | |
| 101 | def float_to_words(value, decimal_sep: str = "point") -> str: |
no test coverage detected