n2words 0.1.1

Convert numbers to words in 50 languages (72 regional variants): cardinal, ordinal and currency forms, with arbitrary-precision input
Documentation
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! French (Belgium) (`fr-BE`).
//!
//! Belgian French differences from standard French:
//! - septante (70) instead of soixante-dix
//! - nonante (90) instead of quatre-vingt-dix
//! - Keeps quatre-vingts (80) like standard French
//! - Uses "septante et un" (71), "nonante et un" (91)
//! - Optional hundred pairing for 1100-1999: dix-neuf cents (1900), dix-neuf cent septante (1970)
//!
//! ```
//! use n2words::fr_be::{to_cardinal, to_currency, to_ordinal};
//!
//! assert_eq!(to_cardinal(70)?, "septante");
//! assert_eq!(to_ordinal(90)?, "nonantième");
//! assert_eq!(to_currency(0.99)?, "nonante-neuf centimes");
//! # Ok::<(), n2words::Error>(())
//! ```

use crate::Result;
use crate::currency::vocab::FR as CURRENCY_VOCAB;
use crate::currency::{Currency, assert_minor_unit};
use crate::language::{Kind, Language, form};
use crate::max::Max;
use crate::number::{
    Number, digits_to_biguint, parse_cardinal, parse_currency, parse_ordinal, split_groups,
};
use crate::options::options;
use num_bigint::BigUint;
use num_traits::{One, ToPrimitive, Zero};

// ============================================================================
// Vocabulary
// ============================================================================

const ONES: [&str; 10] = [
    "", "un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf",
];
const TEENS: [&str; 10] = [
    "dix", "onze", "douze", "treize", "quatorze", "quinze", "seize", "dix-sept", "dix-huit",
    "dix-neuf",
];
const TENS: [&str; 10] = [
    "",
    "",
    "vingt",
    "trente",
    "quarante",
    "cinquante",
    "soixante",
    "septante",
    "quatre-vingt",
    "nonante",
];

// Scale words (long scale with -ard forms)
const SCALES: &[&str] = &["million", "billion", "trillion", "quadrillion"];
const SCALES_ARD: &[&str] = &["milliard", "billiard", "trilliard", "quadrilliard"];

// Long scale: each SCALES entry has a base and an "-ard" form spanning two
// segment groups, so with the units group that's 2 * SCALES.len() + 2 groups
// of 3 digits. Ordinals and currency build on the cardinal, so they share the
// same ceiling.

/// The cardinal ceiling, derived from the scale table: `10^30`.
pub const CARDINAL_MAX: Max = Max::long_scale(SCALES.len() as u32);
/// The ordinal ceiling: `10^30`.
pub const ORDINAL_MAX: Max = Max::long_scale(SCALES.len() as u32);
/// The currency ceiling: `10^30`.
pub const CURRENCY_MAX: Max = Max::long_scale(SCALES.len() as u32);

const THOUSAND: &str = "mille";
const HUNDRED: &str = "cent";
const ZERO: &str = "zéro";
const NEGATIVE: &str = "moins";
const DECIMAL_SEP: &str = "virgule";

// ============================================================================
// Ordinal vocabulary
// ============================================================================

const ORDINAL_SUFFIX: &str = "ième";
const PREMIER: &str = "premier";

// ============================================================================
// Segment building
// ============================================================================

/// Words for a 0-999 segment, with the agreement flags the callers need.
struct Segment {
    /// The words, or empty for zero.
    word: String,
    /// Ends in a plural "cents" (deux cents), which loses its 's' before mille.
    ends_with_cents: bool,
    /// Ends in "quatre-vingts", which loses its 's' before mille.
    ends_with_vingts: bool,
}

/// Builds the words for a 0-999 segment.
fn build_segment(n: u32) -> Segment {
    if n == 0 {
        return Segment {
            word: String::new(),
            ends_with_cents: false,
            ends_with_vingts: false,
        };
    }

    let tens_ones = n % 100;
    let hundreds = (n / 100) as usize;

    let mut parts: Vec<String> = Vec::new();
    let mut ends_with_cents = false;
    let mut ends_with_vingts = false;

    // Hundreds
    if hundreds > 0 {
        if hundreds == 1 {
            parts.push(HUNDRED.to_string());
        } else if tens_ones == 0 {
            parts.push(format!("{} {HUNDRED}s", ONES[hundreds]));
            ends_with_cents = true;
        } else {
            parts.push(format!("{} {HUNDRED}", ONES[hundreds]));
        }
    }

    // Tens and ones - Belgian pattern
    if tens_ones == 0 {
        // Just hundreds
    } else if tens_ones < 10 {
        parts.push(ONES[tens_ones as usize].to_string());
    } else if tens_ones < 20 {
        parts.push(TEENS[(tens_ones - 10) as usize].to_string());
    } else if tens_ones < 70 {
        // 20-69: standard pattern
        let t = (tens_ones / 10) as usize;
        let o = (tens_ones % 10) as usize;
        if o == 0 {
            parts.push(TENS[t].to_string());
        } else if o == 1 {
            parts.push(format!("{} et {}", TENS[t], ONES[1]));
        } else {
            parts.push(format!("{}-{}", TENS[t], ONES[o]));
        }
    } else if tens_ones < 80 {
        // 70-79: septante pattern (Belgian)
        let o = (tens_ones % 10) as usize;
        if o == 0 {
            parts.push("septante".to_string());
        } else if o == 1 {
            parts.push(format!("septante et {}", ONES[1]));
        } else {
            parts.push(format!("septante-{}", ONES[o]));
        }
    } else if tens_ones == 80 {
        // 80: quatre-vingts (same as standard)
        parts.push("quatre-vingts".to_string());
        ends_with_vingts = true;
    } else if tens_ones < 90 {
        // 81-89: quatre-vingt-X (same as standard)
        let remainder = (tens_ones - 80) as usize;
        parts.push(format!("quatre-vingt-{}", ONES[remainder]));
    } else {
        // 90-99: nonante pattern (Belgian)
        let o = (tens_ones % 10) as usize;
        if o == 0 {
            parts.push("nonante".to_string());
        } else if o == 1 {
            parts.push(format!("nonante et {}", ONES[1]));
        } else {
            parts.push(format!("nonante-{}", ONES[o]));
        }
    }

    Segment {
        word: parts.join(" "),
        ends_with_cents,
        ends_with_vingts,
    }
}

// ============================================================================
// Helpers
// ============================================================================

/// The scale word (mille, million, milliard, ...) for a scale group index,
/// agreed with `segment`.
fn scale_word(scale_index: usize, segment: u32) -> String {
    if scale_index == 1 {
        return THOUSAND.to_string();
    }

    if scale_index % 2 == 0 {
        let Some(base_word) = SCALES.get(scale_index / 2 - 1) else {
            return String::new();
        };
        if segment > 1 {
            format!("{base_word}s")
        } else {
            (*base_word).to_string()
        }
    } else {
        let Some(ard_word) = SCALES_ARD.get((scale_index - 1) / 2 - 1) else {
            return THOUSAND.to_string();
        };
        if segment > 1 {
            format!("{ard_word}s")
        } else {
            (*ard_word).to_string()
        }
    }
}

/// Drops the plural 's' of "cents" / "quatre-vingts" before "mille".
fn strip_plural_before_mille(segment: Segment) -> String {
    let mut word = segment.word;
    if segment.ends_with_cents || segment.ends_with_vingts {
        word.pop();
    }
    word
}

/// Replaces every space with a hyphen when the hyphen separator is on.
fn hyphenate(result: String, with_hyphen: bool) -> String {
    if with_hyphen {
        result.replace(' ', "-")
    } else {
        result
    }
}

// ============================================================================
// Cardinal
// ============================================================================

/// Words for a non-negative integer.
fn integer_to_words(n: &BigUint, with_hyphen: bool, hundred_pairing: bool) -> String {
    if n.is_zero() {
        return ZERO.to_string();
    }

    if let Some(small) = n.to_u64() {
        if small < 1000 {
            return hyphenate(build_segment(small as u32).word, with_hyphen);
        }

        // Hundred pairing: 1100-1999 counted in hundreds, "onze cents" to
        // "dix-neuf cent nonante-neuf". Only eleven to nineteen hundreds take
        // this form: 1000-1099 has no "dix cents", and from 2000 on it's
        // always "deux mille ...". "cent" follows its usual agreement: plural
        // when it ends the number (dix-neuf cents), invariable when followed
        // (dix-neuf cent un).
        if hundred_pairing && (1100..=1999).contains(&small) {
            let num = small as u32;
            let tens_ones = num % 100;
            let mut result = format!("{} {HUNDRED}", TEENS[(num / 100 - 10) as usize]);
            if tens_ones == 0 {
                result.push('s');
            } else {
                result.push(' ');
                result.push_str(&build_segment(tens_ones).word);
            }
            return hyphenate(result, with_hyphen);
        }

        if small < 1_000_000 {
            let thousands = (small / 1000) as u32;
            let remainder = (small % 1000) as u32;
            let sep = if with_hyphen { '-' } else { ' ' };

            let mut result = if thousands == 1 {
                THOUSAND.to_string()
            } else {
                let mut words = strip_plural_before_mille(build_segment(thousands));
                words.push(sep);
                words.push_str(THOUSAND);
                words
            };

            if remainder > 0 {
                result.push(sep);
                result.push_str(&build_segment(remainder).word);
            }

            return hyphenate(result, with_hyphen);
        }
    }

    build_large_number_words(n, with_hyphen)
}

/// Words for a number of one million or more, by 3-digit scale groups.
fn build_large_number_words(n: &BigUint, with_hyphen: bool) -> String {
    let segments = split_groups(n, 1000);

    let mut parts: Vec<String> = Vec::new();
    for (scale_index, &segment) in segments.iter().enumerate().rev() {
        if segment == 0 {
            continue;
        }
        let built = build_segment(segment);
        if scale_index == 0 {
            parts.push(built.word);
        } else if scale_index == 1 {
            if segment == 1 {
                parts.push(THOUSAND.to_string());
            } else {
                parts.push(strip_plural_before_mille(built));
                parts.push(scale_word(scale_index, segment));
            }
        } else {
            parts.push(built.word);
            parts.push(scale_word(scale_index, segment));
        }
    }

    let sep = if with_hyphen { "-" } else { " " };
    hyphenate(parts.join(sep), with_hyphen)
}

/// Words for the digits after the decimal point: leading zeros spoken as
/// "zéro" one by one, then the rest as a single number.
fn decimal_part_to_words(decimal: &str, with_hyphen: bool) -> String {
    let sep = if with_hyphen { "-" } else { " " };
    let mut result = String::new();

    let zeros = decimal.bytes().take_while(|&b| b == b'0').count();
    for _ in 0..zeros {
        if !result.is_empty() {
            result.push_str(sep);
        }
        result.push_str(ZERO);
    }

    let remainder = &decimal[zeros..];
    if !remainder.is_empty() {
        if !result.is_empty() {
            result.push_str(sep);
        }
        result.push_str(&integer_to_words(
            &digits_to_biguint(remainder),
            with_hyphen,
            false,
        ));
    }

    result
}

options! {
    /// Options for [`to_cardinal_with`].
    pub struct CardinalOptions {
        /// Use hyphens between words
        with_hyphen_separator: bool = false;
        /// Count hundreds past ten for 1100-1999 (e.g., "dix-neuf cents" instead of "mille neuf cents")
        hundred_pairing: bool = false;
    }
}

/// Spells a number in Belgian French words.
///
/// ```
/// # use n2words::fr_be::to_cardinal;
/// assert_eq!(to_cardinal(95)?, "nonante-cinq");
/// assert_eq!(to_cardinal(4196.42)?, "quatre mille cent nonante-six virgule quarante-deux");
/// # Ok::<(), n2words::Error>(())
/// ```
///
/// # Errors
///
/// [`Error::InvalidNumber`](crate::Error::InvalidNumber) for a malformed
/// value, [`Error::OutOfRange`](crate::Error::OutOfRange) at or past
/// [`CARDINAL_MAX`].
pub fn to_cardinal<'a>(value: impl Into<Number<'a>>) -> Result<String> {
    to_cardinal_with(value, &CardinalOptions::default())
}

/// Spells a number in Belgian French words, with options.
///
/// ```
/// # use n2words::fr_be::{to_cardinal_with, CardinalOptions};
/// let pairing = CardinalOptions { hundred_pairing: true, ..Default::default() };
/// assert_eq!(to_cardinal_with(1970, &pairing)?, "dix-neuf cent septante");
/// let hyphens = CardinalOptions { with_hyphen_separator: true, ..Default::default() };
/// assert_eq!(to_cardinal_with(71, &hyphens)?, "septante-et-un");
/// # Ok::<(), n2words::Error>(())
/// ```
///
/// # Errors
///
/// As [`to_cardinal`].
pub fn to_cardinal_with<'a>(
    value: impl Into<Number<'a>>,
    options: &CardinalOptions,
) -> Result<String> {
    let number = parse_cardinal(&value.into())?;
    // Both the integer part and the fraction's significant digits are spelled
    // via the scale builder, so both must clear the ceiling.
    CARDINAL_MAX.check(&number.integer, number.fraction.as_deref())?;

    let with_hyphen = options.with_hyphen_separator;
    let sep = if with_hyphen { "-" } else { " " };

    let mut result = String::new();
    if number.negative {
        result.push_str(NEGATIVE);
        result.push_str(sep);
    }
    result.push_str(&integer_to_words(
        &number.integer,
        with_hyphen,
        options.hundred_pairing,
    ));
    if let Some(fraction) = &number.fraction {
        result.push_str(sep);
        result.push_str(DECIMAL_SEP);
        result.push_str(sep);
        result.push_str(&decimal_part_to_words(fraction, with_hyphen));
    }
    Ok(result)
}

// ============================================================================
// Ordinal
// ============================================================================

/// Turns a cardinal word into its ordinal form:
/// - drop a final -e before -ième (quatre → quatrième)
/// - cinq → cinquième (a -u- before -ième)
/// - neuf → neuvième (f → v before -ième)
fn cardinal_to_ordinal(cardinal: &str) -> String {
    // cinq → cinquième (add 'u')
    if cardinal.ends_with("cinq") {
        return format!("{cardinal}u{ORDINAL_SUFFIX}");
    }

    // neuf → neuvième (f → v)
    if cardinal.ends_with("neuf") {
        let stem = &cardinal[..cardinal.len() - 1];
        return format!("{stem}v{ORDINAL_SUFFIX}");
    }

    // Drop the plural -s of cents/vingts/millions/etc. (quatre-vingts →
    // quatre-vingtième). "trois" and "six" also end in s, but not as a plural.
    const PLURALS: [&str; 10] = [
        "cents",
        "vingts",
        "millions",
        "milliards",
        "billions",
        "billiards",
        "trillions",
        "trilliards",
        "quadrillions",
        "quadrilliards",
    ];
    if PLURALS.iter().any(|plural| cardinal.ends_with(plural)) {
        let stem = &cardinal[..cardinal.len() - 1];
        return format!("{stem}{ORDINAL_SUFFIX}");
    }

    // Drop a final -e before adding -ième (quatre → quatrième)
    if let Some(stem) = cardinal.strip_suffix('e') {
        return format!("{stem}{ORDINAL_SUFFIX}");
    }

    // Default: just add -ième
    format!("{cardinal}{ORDINAL_SUFFIX}")
}

/// Ordinal words for a positive integer.
fn integer_to_ordinal(n: &BigUint) -> String {
    // Special case: 1 → premier
    if n.is_one() {
        return PREMIER.to_string();
    }

    let cardinal = integer_to_words(n, false, false);

    // "un million" is a count; the rank drops the "un", as "mille" gives
    // "millième": "millionième", "milliardième" (Académie française). With
    // anything after the scale word the "un" stays: "un million unième".
    if let Some(rest) = cardinal.strip_prefix("un ") {
        if !rest.contains(' ') {
            return cardinal_to_ordinal(rest);
        }
    }

    cardinal_to_ordinal(&cardinal)
}

/// Spells a positive integer as a Belgian French ordinal.
///
/// Belgian French ordinals: premier (1st), then cardinal + ième, with
/// quatre → quatrième, cinq → cinquième, neuf → neuvième.
///
/// ```
/// # use n2words::fr_be::to_ordinal;
/// assert_eq!(to_ordinal(1)?, "premier");
/// assert_eq!(to_ordinal(70)?, "septantième");
/// assert_eq!(to_ordinal(91)?, "nonante et unième");
/// # Ok::<(), n2words::Error>(())
/// ```
///
/// # Errors
///
/// [`Error::InvalidOrdinal`](crate::Error::InvalidOrdinal) for zero, a
/// negative or a fraction; [`Error::OutOfRange`](crate::Error::OutOfRange) at
/// or past [`ORDINAL_MAX`].
pub fn to_ordinal<'a>(value: impl Into<Number<'a>>) -> Result<String> {
    let n = parse_ordinal(&value.into())?;
    ORDINAL_MAX.check(&n, None)?;
    Ok(integer_to_ordinal(&n))
}

// ============================================================================
// Currency
// ============================================================================

options! {
    /// Options for [`to_currency_with`].
    pub struct CurrencyOptions {
        /// Use "et" between euros and centimes
        and: bool = true;
        /// ISO 4217 currency code to name the amount in
        currency: Currency = Currency::EUR, table = CURRENCY_VOCAB;
    }
}

/// Spells an amount in euros.
///
/// ```
/// # use n2words::fr_be::to_currency;
/// assert_eq!(to_currency(1)?, "un euro");
/// assert_eq!(to_currency(70.7)?, "septante euros et septante centimes");
/// # Ok::<(), n2words::Error>(())
/// ```
///
/// # Errors
///
/// [`Error::InvalidNumber`](crate::Error::InvalidNumber) for a malformed
/// value, [`Error::OutOfRange`](crate::Error::OutOfRange) at or past
/// [`CURRENCY_MAX`].
pub fn to_currency<'a>(value: impl Into<Number<'a>>) -> Result<String> {
    to_currency_with(value, &CurrencyOptions::default())
}

/// Spells an amount in any currency French has words for.
///
/// ```
/// # use n2words::{fr_be::{to_currency_with, CurrencyOptions}, Currency};
/// let opts = CurrencyOptions { currency: Currency::MAD, and: true };
/// assert_eq!(to_currency_with(71, &opts)?, "septante et un dirhams");
/// let opts = CurrencyOptions { and: false, ..Default::default() };
/// assert_eq!(to_currency_with(42.5, &opts)?, "quarante-deux euros cinquante centimes");
/// # Ok::<(), n2words::Error>(())
/// ```
///
/// # Errors
///
/// As [`to_currency`], plus
/// [`Error::UnsupportedCurrency`](crate::Error::UnsupportedCurrency) for a
/// currency French has no words for and
/// [`Error::NoMinorUnit`](crate::Error::NoMinorUnit) for a fractional amount
/// in a currency without one.
pub fn to_currency_with<'a>(
    value: impl Into<Number<'a>>,
    options: &CurrencyOptions,
) -> Result<String> {
    // The currency decides how many decimal digits the parser keeps: TND read
    // at the default 2 would turn "1.500" into 50 millimes instead of 500.
    let words = CURRENCY_VOCAB.words(options.currency)?;
    let money = parse_currency(&value.into(), options.currency.minor_unit_digits())?;
    CURRENCY_MAX.check(&money.major, None)?; // minor units are <= 999, safe
    assert_minor_unit(money.minor, options.currency)?;

    let mut result = String::new();
    if money.negative {
        result.push_str(NEGATIVE);
        result.push(' ');
    }

    // Major units
    if !money.major.is_zero() || money.minor == 0 {
        result.push_str(&integer_to_words(&money.major, false, false));
        // In French, 0 and 1 are singular: "zéro euro", "un euro"
        let unit = if money.major <= BigUint::from(1u32) {
            words.major_at(0)
        } else {
            words.major_at(1)
        };
        // Million, milliard and the scale words above them are nouns, so a
        // round amount of them takes "de" before what it counts, elided before
        // a vowel: "un million d'euros", "deux milliards de dinars".
        if money.major >= BigUint::from(1_000_000u32) && (&money.major % 1_000_000u32).is_zero() {
            if unit.starts_with(['a', 'e', 'i', 'o', 'u', 'é', 'è', 'ê']) {
                result.push_str(" d'");
            } else {
                result.push_str(" de ");
            }
        } else {
            result.push(' ');
        }
        result.push_str(unit);
    }

    // Minor units
    if money.minor > 0 {
        if !money.major.is_zero() {
            result.push_str(if options.and { " et " } else { " " });
        }
        result.push_str(&integer_to_words(&BigUint::from(money.minor), false, false));
        result.push(' ');
        result.push_str(words.minor_at(if money.minor == 1 { 0 } else { 1 }));
    }

    Ok(result)
}

/// Registry entry for `fr-BE`.
pub static LANGUAGE: Language = Language {
    code: "fr-BE",
    name: "French (Belgium)",
    kind: Kind::Full,
    cardinal: Some(form!(with_options to_cardinal_with, CardinalOptions, CARDINAL_MAX)),
    ordinal: Some(form!(plain to_ordinal, ORDINAL_MAX)),
    currency: Some(form!(with_options to_currency_with, CurrencyOptions, CURRENCY_MAX)),
};