MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / convert_number

Function convert_number

conversions/convert_number_to_words.py:137–197  ·  view source on GitHub ↗

Converts an integer to English words. :param num: The integer to be converted :param system: The numbering system (short, long, or Indian) >>> convert_number(0) 'zero' >>> convert_number(1) 'one' >>> convert_number(100) 'one hundred' >>> convert_number(-100

(
    num: int, system: Literal["short", "long", "indian"] = "short"
)

Source from the content-addressed store, hash-verified

135
136
137def convert_number(
138 num: int, system: Literal["short", "long", "indian"] = "short"
139) -> str:
140 """
141 Converts an integer to English words.
142
143 :param num: The integer to be converted
144 :param system: The numbering system (short, long, or Indian)
145
146 >>> convert_number(0)
147 'zero'
148 >>> convert_number(1)
149 'one'
150 >>> convert_number(100)
151 'one hundred'
152 >>> convert_number(-100)
153 'negative one hundred'
154 >>> convert_number(123_456_789_012_345) # doctest: +NORMALIZE_WHITESPACE
155 'one hundred twenty-three trillion four hundred fifty-six billion
156 seven hundred eighty-nine million twelve thousand three hundred forty-five'
157 >>> convert_number(123_456_789_012_345, "long") # doctest: +NORMALIZE_WHITESPACE
158 'one hundred twenty-three thousand four hundred fifty-six milliard
159 seven hundred eighty-nine million twelve thousand three hundred forty-five'
160 >>> convert_number(12_34_56_78_90_12_345, "indian") # doctest: +NORMALIZE_WHITESPACE
161 'one crore crore twenty-three lakh crore
162 forty-five thousand six hundred seventy-eight crore
163 ninety lakh twelve thousand three hundred forty-five'
164 >>> convert_number(10**18)
165 Traceback (most recent call last):
166 ...
167 ValueError: Input number is too large
168 >>> convert_number(10**21, "long")
169 Traceback (most recent call last):
170 ...
171 ValueError: Input number is too large
172 >>> convert_number(10**19, "indian")
173 Traceback (most recent call last):
174 ...
175 ValueError: Input number is too large
176 """
177 word_groups = []
178
179 if num < 0:
180 word_groups.append("negative")
181 num *= -1
182
183 if num > NumberingSystem.max_value(system):
184 raise ValueError("Input number is too large")
185
186 for power, unit in NumberingSystem[system.upper()].value:
187 digit_group, num = divmod(num, 10**power)
188 if digit_group > 0:
189 word_group = (
190 convert_number(digit_group, system)
191 if digit_group >= 100
192 else convert_small_number(digit_group)
193 )
194 word_groups.append(f"{word_group} {unit}")

Callers 1

Calls 3

convert_small_numberFunction · 0.85
max_valueMethod · 0.80
appendMethod · 0.45

Tested by

no test coverage detected