Given a non-negative amount of US Dollars (USD) as a decimal string amount, convert it into its English words representation as a currency string.
The integer part represents whole dollars and the fractional part, rounded to two decimal places, represents cents. The result must be formatted as "<dollars in words> Dollars and <cents in words> Cents".
Function Signature
def number_to_words_usd(amount: str) -> str:
Rules
-
amount
is a plain decimal string, such as
"123.45"
or
"7"
.
-
Round first, then split. Compute total cents by rounding
amount * 100
to the nearest integer, where an exact half rounds up (
"0.005"
is 1 cent). Dollars are
total_cents // 100
and cents are
total_cents % 100
, so rounding can carry into the dollars.
-
Always include both the
Dollars
and
Cents
portions, even if one of them is zero (use
Zero
in that case). Both words stay plural, so
"1.01"
becomes
"One Dollars and One Cents"
.
-
Capitalize words as in standard English number conversion (for example
One Hundred Twenty Three
), join them with single spaces, and use no hyphens and no inner "and".
-
Use the short scale:
Thousand
,
Million
,
Billion
. Write the dollars in groups of three digits, highest group first, each followed by its scale word. A group that is
000
adds no words.
Constraints
-
0 <= amount <= 999,999,999,999.99
-
amount
may have more than two decimal places; it is rounded to the cent as described in Rules.
Examples
Input: amount = "123.45"
Output: "One Hundred Twenty Three Dollars and Forty Five Cents"
123 dollars read as "One Hundred Twenty Three" and 45 cents read as "Forty Five".
Input: amount = "1000000.07"
Output: "One Million Dollars and Seven Cents"
The thousands and units groups of 1,000,000 are both 000, so only "One Million" is written. The 7 cents read as "Seven".
Input: amount = "1.995"
Output: "Two Dollars and Zero Cents"
1.995 dollars is 199.5 cents, and the exact half rounds up to 200 cents. That is 2 dollars and 0 cents, and the zero cents part is still written out.