Metadata-Version: 2.4
Name: spelledout
Version: 0.2.2
Summary: Numbers and money amounts written out in words for cheques, invoices and contracts, with the grammar right (English, Arabic). Zero dependencies.
License: MIT
Project-URL: Homepage, https://github.com/RealAoss/spelledout
Project-URL: Issues, https://github.com/RealAoss/spelledout/issues
Keywords: number-to-words,num2words,amount-in-words,money,currency,cheque,invoice,arabic,tafqit,spell-out,iso-4217
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: Arabic
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Text Processing :: Linguistic
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# spelledout

**Numbers and money amounts written out in words, with the grammar right.**
For cheques, invoices, contracts and any document where the amount must also
appear in words.

Pure Python, zero dependencies, exact arithmetic (no binary floats).

```python
>>> import spelledout
>>> spelledout.money("1250.50", "USD")
'one thousand two hundred fifty dollars and fifty cents'
>>> spelledout.money("1250.50", "USD", lang="ar", only=True)
'فقط ألف ومئتان وخمسون دولاراً وخمسون سنتاً لا غير'
>>> spelledout.words(1250, style="uk")
'one thousand two hundred and fifty'
>>> spelledout.ordinal(21)
'twenty-first'
>>> spelledout.parse("one thousand two hundred and fifty")
1250
>>> spelledout.check("1250.500", "ألف ومئتان وخمسون ديناراً وخمسمئة فلس فقط لا غير", "KWD").ok
True
```

It also reads the words back and checks that a figure and its words agree:
see [Reading words back](#reading-words-back).

## Why this exists

Writing `1250` as "one thousand two hundred fifty" is easy in English. It is
not easy in languages where the number and the thing it counts must agree,
and Arabic is the hardest common case: the form of the number depends on the
gender of the noun, and the noun changes number and case depending on the
last two digits of the amount.

| Amount | Correct Arabic | What happens |
|---|---|---|
| 1 dinar | دينار واحد | the noun comes first |
| 2 dinars | ديناران | the dual, with no number word at all |
| 3 dinars | ثلاثة دنانير | plural noun; the number takes the *opposite* gender |
| 3 liras | ثلاث ليرات | ... so a feminine noun gets the short form |
| 11 dinars | أحد عشر ديناراً | singular noun again, in the accusative |
| 100 dinars | مئة دينار | singular noun, genitive |
| 2,000 dinars | ألفا دينار | the dual of "thousand" drops its final ن before the noun |

A converter that glues a number to a fixed currency word produces text that
a bank clerk, a notary or a court reads as a mistake. On a cheque or a
contract the amount in words is the legally binding one, so it has to be
exactly right. `spelledout` implements the agreement rules instead of
approximating them, refuses input it cannot write exactly, and never rounds
silently.

## Install

```bash
pip install git+https://github.com/RealAoss/spelledout
```

Python 3.10 or later. No dependencies.

## Usage

### Python

```python
>>> from decimal import Decimal
>>> import spelledout

>>> spelledout.words(1250)
'one thousand two hundred fifty'
>>> spelledout.words("-3.14")
'minus three point one four'
>>> spelledout.words(1234567, system="indian")
'twelve lakh thirty-four thousand five hundred sixty-seven'

>>> spelledout.money(Decimal("1250.50"), "GBP", style="uk", only=True)
'one thousand two hundred and fifty pounds and fifty pence only'
>>> spelledout.money("1250.50", "USD", minor="fraction", only=True)
'one thousand two hundred fifty and 50/100 dollars only'

>>> spelledout.money("2.500", "KWD", lang="ar")
'ديناران وخمسمئة فلس'
>>> spelledout.words(3, lang="ar"), spelledout.words(3, lang="ar", gender="f")
('ثلاثة', 'ثلاث')
>>> spelledout.ordinal(21, lang="ar"), spelledout.ordinal(21, lang="ar", gender="f")
('الحادي والعشرون', 'الحادية والعشرون')
```

Three functions, all returning a `str`:

| Function | Purpose |
|---|---|
| `words(number, lang="en", **options)` | a cardinal number, negative or with decimals |
| `ordinal(number, lang="en", **options)` | an ordinal (whole numbers, zero or above) |
| `money(amount, currency="USD", lang="en", *, rounding=None, only=False, **options)` | an amount with its currency units |

`languages()` and `currencies()` list what is available. Everything the
library refuses raises `spelledout.SpelledOutError` (a `ValueError`) with a
message that says why.

**Input.** A number may be an `int`, a `Decimal`, a string or a `float`.

- Strings are digits with an optional sign and a point as the decimal mark:
  `"1250.50"`, `"-7"`. A comma is accepted only as a thousands separator in
  groups of three (`"1,250.50"`); it is never read as a decimal mark, so
  `"1,25"` is refused. Arabic-Indic digits (`"١٢٥٠"`) are accepted.
- A `float` is read through its `repr`, the shortest string that
  round-trips, so `0.1` is exactly one tenth and never
  `0.1000000000000000055...`. For money, prefer `Decimal` or a string: the
  result of float arithmetic (`1.1 + 2.2`) carries its error with it and will
  be refused as having too many decimals.
- Decimals are kept as written: `words("1.50")` is "one point five zero".

**Decimals of a currency.** The number of decimals comes from ISO 4217:
none for JPY, two for USD, three for KWD. More decimals than that is an
error by default:

```python
>>> spelledout.money("1.234", "USD")
Traceback (most recent call last):
  ...
spelledout.errors.SpelledOutError: USD amounts have at most 2 decimals; got 1.234. Pass rounding='half-even' to round instead
>>> spelledout.money("1.235", "USD", rounding="half-even")
'one dollar and twenty-four cents'
```

`rounding` is `"half-even"` (banker's rounding), `"half-up"` or `"down"`.
Negative amounts are refused.

**Options by language.**

| Language | Option | Values (default first) | Effect |
|---|---|---|---|
| English | `style` | `"us"`, `"uk"` | `"uk"` adds "and": one hundred **and** one |
| English | `system` | `"western"`, `"indian"` | `"indian"` uses lakh and crore |
| English | `minor` (money) | `"words"`, `"fraction"` | `"fraction"`: "and 50/100 dollars" |
| Arabic | `gender` | `"m"`, `"f"` | gender of the thing counted (not for `money`: the currency decides) |
| Arabic | `case` | `"nominative"`, `"genitive"`, `"accusative"` | ألفان / ألفين, عشرون / عشرين |
| Arabic | `hundred` | `"مئة"`, `"مائة"` | spelling of "hundred" |
| all | `only` (money) | `False`, `True` | "... only" / "فقط ... لا غير" |

### Command line

```console
$ spelledout 1250.50 --currency USD --lang en
one thousand two hundred fifty dollars and fifty cents
$ spelledout 1250.50 -c KWD -l ar --only
فقط ألف ومئتان وخمسون ديناراً وخمسمئة فلس لا غير
$ spelledout 21 --ordinal
twenty-first
$ spelledout 1.234 -c USD
spelledout: error: USD amounts have at most 2 decimals; got 1.234. Pass rounding='half-even' to round instead
```

`python -m spelledout` works the same way. `spelledout --help` lists every
option (`--style`, `--system`, `--minor`, `--gender`, `--case`, `--hundred`,
`--round`, `--list-currencies`, `--list-languages`). The exit status is 0 on
success and 2 when the input cannot be written out.

## Reading words back

Since 0.2.0 the library also goes the other way: words to a number, and a
check that a figure and its words say the same thing. This is the part to
use on a cheque, an invoice or a contract, where both forms appear and must
agree.

```python
>>> from decimal import Decimal
>>> import spelledout

>>> spelledout.parse("one thousand two hundred and fifty")
1250
>>> spelledout.parse("Twelve Hundred")
1200
>>> spelledout.parse("minus three point one four")
Decimal('-3.14')
>>> spelledout.parse("ألف ومئتان وخمسون", lang="ar")
1250
>>> spelledout.parse("الف ومائتين وخمسين", lang="ar")
1250

>>> spelledout.parse_money("three euros and twenty cents")
Money(amount=Decimal('3.20'), currency='EUR', major=3, minor=20, candidates=('EUR',))
>>> spelledout.parse_money("ألف ومئتان وخمسون ديناراً وخمسمئة فلس فقط لا غير", lang="ar")
Money(amount=Decimal('1250.500'), currency=None, major=1250, minor=500, candidates=('BHD', 'IQD', 'JOD', 'KWD'))
>>> spelledout.parse_money("ألف دينار كويتي", lang="ar").currency
'KWD'
>>> spelledout.parse_money("two dinars and five hundred fils", currency="JOD").amount
Decimal('2.500')

>>> result = spelledout.check("1250.500", "one thousand two hundred fifty dinars and five hundred fils", "KWD")
>>> result.ok
True
>>> result = spelledout.check("1520.500", "ألف ومئتان وخمسون ديناراً وخمسمئة فلس", "KWD")
>>> result.ok, result.reason
(False, 'the main amount differs: the words say 1250 (dinar), the figure says 1520')
```

| Function | Returns |
|---|---|
| `parse(text, lang="en")` | an `int`, or a `Decimal` when the words have a decimal part (digits kept as written) |
| `parse_money(text, lang="en", currency=None)` | a `Money`: `amount` (`Decimal`), `currency` (ISO code or `None`), `major`, `minor`, `candidates` |
| `check(amount, text, currency=None, lang=None)` | a `CheckResult`: `ok`, `parsed`, `expected`, `reason`; truthy when they agree |

`lang=None` picks the language from the script (any Arabic letter means
Arabic). `check` detects it by default.

### Strict by design

The readers never skip a word and never pick one of two readings. Text that
is not a well-formed number raises `spelledout.ParseError` (a
`SpelledOutError`, so also a `ValueError`) carrying the offending `word`,
its `position` (zero-based character offset) and its `index` (zero-based
word number).

```python
>>> spelledout.parse("twenty thirty")
Traceback (most recent call last):
    ...
spelledout.errors.ParseError: this word cannot follow 'twenty': 'thirty' (word 2, character offset 7)
>>> try:
...     spelledout.parse("ثلاثة عشرين", lang="ar")
... except spelledout.ParseError as error:
...     print(error.word, error.position, error.index)
عشرين 6 1
>>> spelledout.parse("hundred hundred")
Traceback (most recent call last):
    ...
spelledout.errors.ParseError: a number is expected before this word (write 'one hundred', 'one thousand'): 'hundred' (word 1, character offset 0)
```

What is checked is what changes the value: the order of the parts, a scale
word used twice, a missing و, a unit after a ten. What is not checked is
grammar that leaves the value alone: gender, case and number agreement in
Arabic (ثلاث دنانير and خمسة دينار are read as 3 and 5 dinars), singular
or plural of an English unit ("five dollar").

### Shared currency names

Most unit words belong to several currencies. "Dinar" is the unit of seven
of the supported currencies, "dollar" of six, ريال of five. `parse_money`
does not guess:

- `currency` is an ISO code only when exactly one supported currency fits
  the words; otherwise it is `None`. `candidates` always lists every code
  that fits, in alphabetical order.
- The sub-unit narrows the list: dinars with fils are BHD, IQD, JOD or KWD;
  dinars with millimes are TND; riyals with halalas are SAR.
- A country name next to the unit settles it: "Kuwaiti dinars",
  "US dollars", "pounds sterling", دينار كويتي, جنيه مصري, ريالاً سعودياً.
- So does the `currency=` argument, which also checks that the words fit
  that currency.

```python
>>> spelledout.parse_money("five dollars").candidates
('AUD', 'CAD', 'HKD', 'NZD', 'SGD', 'USD')
>>> spelledout.parse_money("five hundred US dollars").currency
'USD'
>>> spelledout.parse_money("twenty riyals and fifty halalas").currency
'SAR'
```

Sometimes the candidates do not even agree on the amount. A fils is a
thousandth of a Kuwaiti dinar and a hundredth of a UAE dirham; a dirham is
the UAE and Moroccan unit and also the sub-unit of the Qatari riyal and the
Libyan dinar. When the amount depends on the choice, `parse_money` raises
`AmbiguousAmountError` (its `readings` maps each code to its amount)
instead of returning one of them:

```python
>>> spelledout.parse_money("five fils")
Traceback (most recent call last):
    ...
spelledout.errors.AmbiguousAmountError: the unit words fit currencies that give different amounts: 0.05 (AED, YER); 0.005 (BHD, IQD, JOD, KWD). Pass currency= to choose one
>>> spelledout.parse_money("five fils", currency="KWD").amount
Decimal('0.005')
>>> spelledout.parse_money("fifty dirhams", currency="AED").amount
Decimal('50.00')
>>> spelledout.parse_money("fifty dirhams", currency="QAR").amount
Decimal('0.50')
```

This means a bare "fifty dirhams" or خمسمئة درهم is refused until the
currency is named. That is deliberate: the same words are what this
library writes for 0.50 QAR and 0.500 LYD.

The number of decimals follows the currency: 2.500 for KWD, 2.50 for USD,
500 for JPY. A sub-unit amount that is not less than one unit ("one dollar
and one hundred cents") is refused. When the candidates have different
numbers of decimals and there is no sub-unit ("five dinars": DZD has two,
the others three), `amount` is the whole number.

### Checking a figure against its words

`check(amount, text, currency=None, lang=None)` compares exactly; nothing
is rounded.

- With `currency`, the words must be an amount in that currency. Words with
  no unit at all ("one thousand two hundred fifty") are compared as a plain
  number, and the reason says that no currency was named. Words that read
  both ways are taken as an amount in that currency: خمسين is fifty, but
  with `"MRU"` it is two khoums (0.40), which is what `money()` writes.
- Without `currency`, the words may be a plain number or an amount in any
  currency; the check passes when at least one reading of the words equals
  the figure, and `parsed.candidates` lists the currencies of that reading.
- Words that cannot be read are a failed check (`ok=False`, `parsed=None`,
  the parser's message in `reason`), not an exception. So is a figure the
  currency cannot hold (1.234 USD, a negative amount).
- Only a bad request raises: an `amount` that is not a number, an unknown
  currency or language.

```python
>>> spelledout.check("1250.500", "one thousand two hundred fifteen dinars and five hundred fils", "KWD").reason
'the main amount differs: the words say 1215 (dinar), the figure says 1250'
>>> spelledout.check("1250.500", "one thousand two hundred fifty dinars", "KWD").reason
'the sub-unit amount differs: the words say 0 (fils), the figure says 500'
>>> spelledout.check("1250.50", "one thousand two hundred fifty dollars and fifty cents", "KWD").reason
'the words do not describe an amount in KWD; they fit AUD, CAD, HKD, NZD, SGD, USD'
>>> bool(spelledout.check(1250, "ألف ومئتان وخمسون"))
True
```

### What is accepted

Everything `words()` and `money()` write, in every option, is read back to
the same value (the tests check this for every integer up to 9,999, for
samples up to 10^15, and for all 41 currencies). Beyond that:

**English**

- with or without "and" (after "hundred" or after a scale word, nowhere
  else); hyphens or spaces; any case; commas; a final full stop; an outer
  pair of brackets or quotes;
- "a hundred", "a thousand", "a million"; "twelve hundred" (eleven to
  ninety-nine hundred, not a multiple of ten, as the whole number);
- "point" decimals read digit by digit, also a bare "point five";
  "minus" or "negative"; "zero" or "nil";
- the short scale up to decillion (below 10^36); lakh / lac and crore, never
  mixed with million and above;
- a final "only";
- money: unit after the number ("five dollars"), or before it ("Rupees five
  thousand and paise fifty"); "and", a comma or nothing between unit and
  sub-unit; the cheque fraction "and 50/100 dollars" or
  "dollars and 50/100" (also `no/100`, `xx/100`); "a dollar", "no cents";
  plural or singular unit; the spellings riyal / rial, rouble, kopek,
  piaster, pence, paise, agorot, reais; "lira" also for the Lebanese and
  Syrian pounds;
- country names before the unit: US, U.S., American, Canadian, Australian,
  New Zealand, Singapore, Hong Kong, British, Swiss, Japanese, Chinese,
  Indian, Pakistani, Turkish, Russian, Brazilian, Mexican, South African,
  South Korean, Israeli, Saudi, Emirati, UAE, Qatari, Kuwaiti, Bahraini,
  Omani, Jordanian, Iraqi, Egyptian, Sudanese, Syrian, Lebanese, Yemeni,
  Libyan, Tunisian, Algerian, Moroccan, Mauritanian, Somali, Djiboutian,
  Comorian; and "sterling" after "pounds".

**Arabic**

- with or without short vowels, tanween, shadda and tatweel;
- hamza and alif variants (أ / إ / آ / ا), ة or ه at the end of a word,
  ى or ي: أربعة, اربعة and اربعه are the same word;
- both spellings of hundred and of the compounds: مئة / مائة,
  ثلاثمئة / ثلاثمائة / ثلاث مئة / ثلاث مائة, ثمانمئة / ثماني مئة;
- nominative and oblique forms: اثنان / اثنين, مئتان / مئتين, ألفان / ألفين,
  عشرون / عشرين, مليونان / مليونين, and the construct forms مئتا / مئتي,
  ألفا / ألفي before a noun;
- masculine and feminine forms: ثلاثة / ثلاث, واحد / واحدة,
  أحد عشر / إحدى عشرة, اثنا عشر / اثنتا عشرة, ثمانٍ / ثماني / ثمانياً;
- singular, accusative and plural scale words after a number (ألف, ألفاً,
  آلاف; مليون, ملايين; مليار, مليارات; بليون, بلايين; تريليون or ترليون,
  تريليونات), and their duals standing alone;
- و attached (وخمسون) or written apart (و خمسون);
- فقط at either end and لا غير at the end;
- سالب or ناقص for a negative number, صفر, and decimals read digit by
  digit after فاصلة;
- money: singular, dual, plural and accusative forms of every unit the
  library writes; دينار واحد and a bare دينار for one, ديناران for two;
  the repeated noun of مئة دينار ودينار واحد; the spellings شيقل / شواقل
  and the plural ملاليم; a country adjective after the unit in any of its
  agreement forms (كويتي, كويتية, كويتياً, كويتيان, كويتيين ...) for every
  currency except EUR, HKD, ZAR and KRW.
- **Colloquial forms, complete list:** اتنين (2), تلاتة and تلات (3),
  تمانية (8), تلاتين (30), تمانين (80), مية (100), ميتين (200), تلتمية and
  تلاتمية (300), ربعمية and أربعمية (400), خمسمية (500), ستمية (600),
  سبعمية (700), تمنمية and تمانمية (800), تسعمية (900). Nothing else:
  no colloquial 11-19 (حداشر ...), no other dialect spellings.

### What is not accepted

These raise `ParseError`; none of them is read as something else.

- Ordinals ("twenty-first", الثالث) and fractions ("a half", "one and a
  half", نصف, ربع).
- Digits inside the words ("5 thousand", "١٢٥٠"), except the cheque
  fraction `50/100`. Currency symbols and ISO codes in the text ("$", "USD").
- Years and telephone style ("nineteen ninety-nine", "one oh five"),
  "dozen", "twenty hundred", "hundred" or "thousand" with no number before
  it, a scale word used twice or out of order.
- Decimals read as a number ("three point fourteen") and decimals or a
  minus sign in a money amount.
- Arabic: a missing و between parts (ألف مئتان); the unit after the ten
  (عشرون وثلاثة); the smallest part first (خمسة وألف); the long unit before
  مئة (ثلاثة مئة); a number before a dual (ثلاثة ألفان); the definite
  article (الألف); an unvowelled ألفا with no number before it and no noun
  after it (it could be ألفاً, one thousand, or the dual ألفا, two
  thousand: write ألفان or ألف).
- Money: two sub-units, a sub-unit that does not belong to the unit
  ("dinars and cents"), the sub-unit before the unit, a country name that
  does not go with the unit ("Kuwaiti dollars").
- بليون is read as 10^9, the same as مليار. If your document uses it for
  10^12, do not rely on this reader.

### Command line

```console
$ spelledout parse "one thousand two hundred and fifty"
1250
$ spelledout parse "two dinars and five hundred fils"
2.500 (BHD, IQD, JOD, KWD)
$ spelledout parse "ديناران وخمسمئة فلس" --currency KWD --json
{"kind": "money", "amount": "2.500", "currency": "KWD", "candidates": ["KWD"], "major": 2, "minor": 500}
$ spelledout check 1250.500 "ألف ومئتان وخمسون ديناراً وخمسمئة فلس" --currency KWD
OK: the words and the figure agree
$ spelledout check 1520.500 "ألف ومئتان وخمسون ديناراً وخمسمئة فلس" --currency KWD
MISMATCH: the main amount differs: the words say 1250 (dinar), the figure says 1520
```

`parse` and `check` take `--lang` (default: detected from the script),
`--currency` and `--json`. `check` exits with 0 when the figure and the
words agree and 1 when they do not; both exit with 2 when the request
itself is wrong (and `parse` when the words cannot be read).

## Supported languages

| Code | Language | Cardinals | Ordinals | Money | Reading back |
|---|---|---|---|---|---|
| `en` | English | below 10^36 (10^14 in the Indian system) | yes | yes | cardinals and money |
| `ar` | Arabic (Modern Standard) | below 10^15 | 1 to 99 | yes | cardinals and money |

## The Arabic grammar it gets right

**The number word**

| Rule | Counting a masculine noun | Counting a feminine noun |
|---|---|---|
| 1 and 2 agree with the noun | واحد, اثنان | واحدة, اثنتان |
| 3-10 take the opposite gender | ثلاثة, عشرة | ثلاث, عشر |
| 11 and 12 agree in both parts | أحد عشر, اثنا عشر | إحدى عشرة, اثنتا عشرة |
| 13-19: unit opposite, ten agrees | ثلاثة عشر | ثلاث عشرة |
| 21-99: unit, then و, then the ten | واحد وعشرون, خمسة وعشرون | إحدى وعشرون, خمس وعشرون |
| eight before a feminine noun | ثمانية دنانير | ثماني ليرات, ثماني عشرة ليرة |

Hundreds are one word (مئة, مئتان, ثلاثمئة ... تسعمئة). Thousands, millions,
billions and trillions are themselves masculine nouns and are counted like
any other noun: ألف, ألفان, ثلاثة آلاف, أحد عشر ألفاً, مئة ألف, مليونان,
ثلاثة ملايين. The parts run from the largest to the smallest, joined with و:
`1,234,567` is مليون ومئتان وأربعة وثلاثون ألفاً وخمسمئة وسبعة وستون.

**The counted noun** follows the last two digits of the amount:

| Last two digits | Noun | Masculine (دينار) | Feminine (ليرة) |
|---|---|---|---|
| exactly 1 | singular + واحد / واحدة | دينار واحد | ليرة واحدة |
| exactly 2 | dual, no number word | ديناران | ليرتان |
| 03-10 | plural | ثلاثة دنانير, مئة وثلاثة دنانير | ثلاث ليرات |
| 11-99 | singular, accusative | أحد عشر ديناراً, عشرون ديناراً | إحدى عشرة ليرة |
| 00 | singular | مئة دينار, ألف دينار, مليون دينار | مئة ليرة |
| 00 after a dual | the dual drops its ن | مئتا دينار, ألفا دينار, مليونا دينار | مئتا ليرة, ألفا ليرة |
| 01, 02 above 100 | round part + noun, then the noun again | مئة دينار ودينار واحد, ألف دينار وديناران | مئة ليرة وليرة واحدة |

The same rule applies to a scale word when a noun follows:
أحد عشر ألفاً, but أحد عشر ألف دينار. And sub-units are counted with their
own gender: `3.03 SAR` is ثلاثة ريالات وثلاث هللات.

## Conventions chosen

Where usage varies, `spelledout` picks one documented form.

**Arabic**

- **Case: nominative by default** (ألفان, مئتان, عشرون, اثنا عشر). This is
  the form taught for writing amounts, including the cheque formula
  فقط ... لا غير. Pass `case="genitive"` or `case="accusative"` when the
  amount sits in a sentence that requires it (بمبلغ ألفين وخمسين ديناراً);
  the two give the same written forms except for the feminine ثمانٍ / ثمانياً.
- **No short vowels.** The only marks written are the tanween of the
  accusative singular (ديناراً, ألفاً), placed on the alif, and of ثمانٍ.
- **مئة**, not مائة, unless you pass `hundred="مائة"` (then ثلاثمائة, مائتان).
- **1 and 2 with a noun**: دينار واحد and ديناران, never واحد دينار.
- **101, 102 ...**: the classical مئة دينار ودينار واحد and
  مئة ألف وألف, not the colloquial مئة وواحد دينار.
- **Scale**: مليار is 10^9 and تريليون is 10^12.
- **Decimals** of a plain number are read digit by digit after فاصلة:
  `3.14` is ثلاثة فاصلة واحد أربعة.
- **Negative** numbers start with سالب.
- **Foreign nouns that do not inflect** (يورو, بيزو, يوان, وون, راند,
  سنتافو) stay unchanged after every number: خمسة يورو, اثنان يورو.
- **Currency nouns are bare**: دولار, not دولار أمريكي; جنيه for EGP, SDG
  and GBP; ليرة for LBP, SYP and TRY. Add the adjective yourself if the
  document needs it.
- **Ordinals** carry the definite article: الأول, الحادي عشر, العشرون.
- **Zero units are left out**: `0.50 USD` is خمسون سنتاً, and `5.00` is
  خمسة دولارات.

**English**

- US wording by default (one hundred one); `style="uk"` gives the British
  "and" (one hundred and one, one thousand and one).
- Short scale (billion = 10^9); hyphenated tens and units (twenty-one).
- Units and sub-units are joined with "and"; zero sub-units are left out
  ("five dollars"), and so is a zero unit ("fifty cents").
- Decimals of a plain number are read digit by digit after "point".
- Currency nouns are bare ("dollars", not "US dollars").

## Supported currencies

Decimals are the ISO 4217 minor-unit exponent.

| Code | Decimals | English | Arabic |
|---|---|---|---|
| AED | 2 | dirham / fils | درهم / فلس |
| AUD | 2 | dollar / cent | دولار / سنت |
| BHD | 3 | dinar / fils | دينار / فلس |
| BRL | 2 | real / centavo | ريال / سنتافو |
| CAD | 2 | dollar / cent | دولار / سنت |
| CHF | 2 | franc / centime | فرنك / سنتيم |
| CNY | 2 | yuan / fen | يوان / فن |
| DJF | 0 | franc | فرنك |
| DZD | 2 | dinar / centime | دينار / سنتيم |
| EGP | 2 | pound / piastre | جنيه / قرش |
| EUR | 2 | euro / cent | يورو / سنت |
| GBP | 2 | pound / penny | جنيه / بنس |
| HKD | 2 | dollar / cent | دولار / سنت |
| ILS | 2 | shekel / agora | شيكل / أغورة |
| INR | 2 | rupee / paisa | روبية / بيسة |
| IQD | 3 | dinar / fils | دينار / فلس |
| JOD | 3 | dinar / fils | دينار / فلس |
| JPY | 0 | yen | ين |
| KMF | 0 | franc | فرنك |
| KRW | 0 | won | وون |
| KWD | 3 | dinar / fils | دينار / فلس |
| LBP | 2 | pound / piastre | ليرة / قرش |
| LYD | 3 | dinar / dirham | دينار / درهم |
| MAD | 2 | dirham / centime | درهم / سنتيم |
| MRU | 2 (steps of 0.2) | ouguiya / khoums | أوقية / خمس |
| MXN | 2 | peso / centavo | بيزو / سنتافو |
| NZD | 2 | dollar / cent | دولار / سنت |
| OMR | 3 | rial / baisa | ريال / بيسة |
| PKR | 2 | rupee / paisa | روبية / بيسة |
| QAR | 2 | riyal / dirham | ريال / درهم |
| RUB | 2 | ruble / kopeck | روبل / كوبيك |
| SAR | 2 | riyal / halala | ريال / هللة |
| SDG | 2 | pound / piastre | جنيه / قرش |
| SGD | 2 | dollar / cent | دولار / سنت |
| SOS | 2 | shilling / cent | شلن / سنت |
| SYP | 2 | pound / piastre | ليرة / قرش |
| TND | 3 | dinar / millime | دينار / مليم |
| TRY | 2 | lira / kurus | ليرة / قرش |
| USD | 2 | dollar / cent | دولار / سنت |
| YER | 2 | rial / fils | ريال / فلس |
| ZAR | 2 | rand / cent | راند / سنت |

The Mauritanian ouguiya is divided into 5 khoums, so MRU amounts must be a
multiple of 0.2.

## Limitations

Please read these before using the output on a legal or financial document.

- **Have a native speaker review the output before it goes on a legal
  instrument.** The rules were implemented and tested with care (several
  hundred hand-written expected strings), but this is an early version and
  it has not been audited by a bank, a court or a language academy. You are
  responsible for the text you sign.
- Banks and jurisdictions have house styles (oblique case, مائة, a currency
  adjective, "and no cents"). The options cover the common ones; they do not
  cover all of them.
- Two languages only: English and Arabic. No French, Spanish, Hebrew ... yet.
- Arabic ordinals stop at 99, Arabic numbers at 10^15, English at 10^36.
- Arabic plain numbers do not take the definite article and are not
  inflected for case beyond the dual and the tens (which is all that shows
  in unvowelled writing, apart from ثمانٍ).
- A few Arabic sub-unit names of non-Arab currencies are transliterations
  with more than one spelling in use (فن for the Chinese fen, بيسة for the
  Indian and Pakistani paisa, شواكل as the plural of شيكل). Check them
  against the usage of your country.
- Negative money amounts are refused; no "minus" or parentheses wording.
- Only one sub-unit per currency (no Jordanian piastres or Egyptian
  milliemes), no historical currencies, no cryptocurrencies.
- It does not format digits (`1,250.50`).
- Writing: no fractions ("one half"), no years or dates, no English
  "a hundred", no all-capitals cheque style (use `.upper()` or `.title()`).
- Reading words back has its own limits, listed under
  [What is not accepted](#what-is-not-accepted): cardinals and money only,
  no ordinals, no fractions, a short fixed list of colloquial Arabic forms,
  and shared currency names are reported as candidates, not resolved.
- The Arabic reader was tested against what this library writes and
  against hand-written variants. It has not been run over a corpus of real
  cheques or contracts, and no native-speaker review of the accepted
  variants has taken place. Treat a refusal as "look at this by hand", and
  report forms that should be accepted.

## Adding a language

A language is **one file**, `src/spelledout/lang/<code>.py`. It is found
automatically; nothing else needs to be registered.

```python
from ..numfmt import split_decimal
from .base import Language

class French(Language):
    code = "fr"
    name = "French"
    limit = 10 ** 15                      # numbers must be below this
    units = {"euro": ..., "cent": ...}    # one entry per unit id, shape is yours

    def to_words(self, value, **options): ...        # value: int or Decimal
    def ordinal(self, n, **options): ...             # n: int >= 0
    def money_to_words(self, main, sub, currency, only=False, **options): ...

LANG = French()
```

`src/spelledout/lang/base.py` documents the interface, and
`src/spelledout/lang/en.py` is a complete example in about 150 lines. The
test-suite checks that every language can write every currency. Reading
words back is separate and optional for a new language: the readers live in
`src/spelledout/_parse_en.py` and `_parse_ar.py`, and `parse` refuses a
language that has none. See
[CONTRIBUTING.md](CONTRIBUTING.md) for what a new language needs before it
can be merged.

## Contributing

Corrections from native speakers, bank and court house styles, new
currencies and new languages are all welcome. See
[CONTRIBUTING.md](CONTRIBUTING.md). Run the tests with:

```bash
python -m unittest discover -s tests
```

`bench/run.py` scores the readers on a blind set of texts,
`bench/blind.py`, written by someone who has not seen the parser. It prints
the accuracy per list and language and every failure, and skips when the
file is absent.

Result of the one run made after the parser was finished (nothing was changed
afterwards): 688 of 708 correct.

| list | English | Arabic |
|---|---|---|
| numbers in words | 185/185 | 253/269 |
| money amounts | 93/94 | 91/94 |
| malformed text that must be refused | 36/36 | 30/30 |

All 20 failures are refusals; none is a wrong number. Sixteen are colloquial
Arabic teens (the حداشر / خمسطعش family), which are not supported. One is a
cheque preamble (مبلغ وقدره) before the amount. Three are a bare "dirhams"
with no country, which the reader refuses because the candidates disagree on
the amount (a dirham is a main unit in two currencies and a sub-unit in two
others); the blind set's author expected the plain number.

## License

MIT. See [LICENSE](LICENSE).
