Skip to main content

inflect_rs/
numbers.rs

1use std::fmt::Display;
2use std::sync::LazyLock;
3
4use fancy_regex::{Captures, Regex};
5
6use crate::data::{nth, MILL, NTH_SUFF, ORDINAL, TEEN, TEN, UNIT};
7use crate::text::{chop, regex};
8use crate::{Engine, Error, NumberToWordsOptions};
9
10static DIGIT_GROUP: LazyLock<Regex> = LazyLock::new(|| regex(r"(\d)"));
11static TWO_DIGITS: LazyLock<Regex> = LazyLock::new(|| regex(r"(\d)(\d)"));
12static THREE_DIGITS: LazyLock<Regex> = LazyLock::new(|| regex(r"(\d)(\d)(\d)"));
13static THREE_DIGITS_WORD: LazyLock<Regex> = LazyLock::new(|| regex(r"(\d)(\d)(\d)(?=\D*\z)"));
14static TWO_DIGITS_WORD: LazyLock<Regex> = LazyLock::new(|| regex(r"(\d)(\d)(?=\D*\z)"));
15static ONE_DIGIT_WORD: LazyLock<Regex> = LazyLock::new(|| regex(r"(\d)(?=\D*\z)"));
16static FOUR_DIGIT_COMMA: LazyLock<Regex> = LazyLock::new(|| regex(r"(\d)(\d{3}(?:,|\z))"));
17static NON_DIGIT: LazyLock<Regex> = LazyLock::new(|| regex(r"\D"));
18static WHITESPACES_COMMA: LazyLock<Regex> = LazyLock::new(|| regex(r"\s+,"));
19static COMMA_WORD: LazyLock<Regex> = LazyLock::new(|| regex(r", (\S+)\s+\z"));
20static WHITESPACES: LazyLock<Regex> = LazyLock::new(|| regex(r"\s+"));
21
22fn sub(
23    re: &Regex,
24    text: &str,
25    limit: Option<usize>,
26    mut replace: impl FnMut(&Captures<'_, str>) -> Result<String, Error>,
27) -> Result<String, Error> {
28    let mut out = String::with_capacity(text.len());
29    let mut last = 0;
30    for caps in re.captures_iter(text).take(limit.unwrap_or(usize::MAX)) {
31        let Ok(caps) = caps else { break };
32        let whole = caps.get(0).expect("group 0 always matches");
33        out.push_str(&text[last..whole.start()]);
34        out.push_str(&replace(&caps)?);
35        last = whole.end();
36    }
37    out.push_str(&text[last..]);
38    Ok(out)
39}
40
41fn digit(caps: &Captures<'_, str>, index: usize) -> usize {
42    caps.get(index)
43        .and_then(|m| m.as_str().chars().next())
44        .and_then(|c| c.to_digit(10))
45        .map_or(0, |d| d as usize)
46}
47
48fn millfn(index: usize) -> Result<&'static str, Error> {
49    MILL.get(index).copied().ok_or(Error::NumOutOfRange)
50}
51
52fn unitfn(units: usize, mindex: usize) -> Result<String, Error> {
53    Ok(format!("{}{}", UNIT[units], millfn(mindex)?))
54}
55
56fn tenfn(tens: usize, units: usize, mindex: usize) -> Result<String, Error> {
57    if tens == 1 {
58        return Ok(format!("{}{}", TEEN[units], millfn(mindex)?));
59    }
60    let hyphen = if tens > 0 && units > 0 { "-" } else { "" };
61    Ok(format!(
62        "{}{hyphen}{}{}",
63        TEN[tens],
64        UNIT[units],
65        millfn(mindex)?
66    ))
67}
68
69fn sub_ord(val: &str) -> String {
70    ORDINAL
71        .iter()
72        .find_map(|(cardinal, ordinal)| {
73            val.strip_suffix(cardinal)
74                .map(|stem| format!("{stem}{ordinal}"))
75        })
76        .unwrap_or_else(|| format!("{val}th"))
77}
78
79fn last_two_digits(s: &str) -> u32 {
80    let s = s.trim();
81    let digits = s.len() - s.trim_end_matches(|c: char| c.is_ascii_digit()).len();
82    let start = s.len() - digits.min(2);
83    s[start..].parse().unwrap_or(0)
84}
85
86struct Words<'a> {
87    andword: &'a str,
88    zero: &'a str,
89    one: &'a str,
90    mill_count: usize,
91}
92
93impl Words<'_> {
94    fn hundfn(&self, hundreds: usize, tens: usize, units: usize) -> Result<String, Error> {
95        if hundreds == 0 && tens == 0 && units == 0 {
96            return Ok(String::new());
97        }
98        let mill = millfn(self.mill_count)?;
99        if hundreds > 0 {
100            let andword = if tens > 0 || units > 0 {
101                format!(" {} ", self.andword)
102            } else {
103                String::new()
104            };
105            return Ok(format!(
106                "{} hundred{andword}{}{mill}, ",
107                UNIT[hundreds],
108                tenfn(tens, units, 0)?
109            ));
110        }
111        Ok(format!("{}{mill}, ", tenfn(tens, units, 0)?))
112    }
113
114    fn group1sub(&self, caps: &Captures<'_, str>) -> Result<String, Error> {
115        Ok(match digit(caps, 1) {
116            1 => format!(" {}, ", self.one),
117            0 => format!(" {}, ", self.zero),
118            units => format!("{}, ", UNIT[units]),
119        })
120    }
121
122    fn group1bsub(&self, caps: &Captures<'_, str>) -> Result<String, Error> {
123        Ok(match digit(caps, 1) {
124            0 => format!(" {}, ", self.zero),
125            units => format!("{}, ", UNIT[units]),
126        })
127    }
128
129    fn group2sub(&self, caps: &Captures<'_, str>) -> Result<String, Error> {
130        let (tens, units) = (digit(caps, 1), digit(caps, 2));
131        if tens > 0 {
132            return Ok(format!("{}, ", tenfn(tens, units, 0)?));
133        }
134        if units > 0 {
135            return Ok(format!(" {} {}, ", self.zero, UNIT[units]));
136        }
137        Ok(format!(" {} {}, ", self.zero, self.zero))
138    }
139
140    fn group3sub(&self, caps: &Captures<'_, str>) -> Result<String, Error> {
141        let (hundreds, tens, units) = (digit(caps, 1), digit(caps, 2), digit(caps, 3));
142        let hunword = match hundreds {
143            1 => format!(" {}", self.one),
144            0 => format!(" {}", self.zero),
145            h => UNIT[h].to_string(),
146        };
147        let tenword = if tens > 0 {
148            tenfn(tens, units, 0)?
149        } else if units > 0 {
150            format!(" {} {}", self.zero, UNIT[units])
151        } else {
152            format!(" {} {}", self.zero, self.zero)
153        };
154        Ok(format!("{hunword} {tenword}, "))
155    }
156
157    fn enword(&mut self, num: &str, group: u8) -> Result<String, Error> {
158        match group {
159            1 => sub(&DIGIT_GROUP, num, None, |c| self.group1sub(c)),
160            2 => {
161                let num = sub(&TWO_DIGITS, num, None, |c| self.group2sub(c))?;
162                sub(&DIGIT_GROUP, &num, Some(1), |c| self.group1bsub(c))
163            }
164            3 => {
165                let num = sub(&THREE_DIGITS, num, None, |c| self.group3sub(c))?;
166                let num = sub(&TWO_DIGITS, &num, Some(1), |c| self.group2sub(c))?;
167                sub(&DIGIT_GROUP, &num, Some(1), |c| self.group1sub(c))
168            }
169            _ => {
170                let mut num = num.trim_start().trim_start_matches('0').to_string();
171                if num.chars().all(|c| c == '0') {
172                    return Ok(self.zero.to_string());
173                }
174                if num == "1" {
175                    return Ok(self.one.to_string());
176                }
177                self.mill_count = 0;
178                while THREE_DIGITS_WORD.is_match(&num).unwrap_or(false) {
179                    num = sub(&THREE_DIGITS_WORD, &num, Some(1), |c| {
180                        let words = self.hundfn(digit(c, 1), digit(c, 2), digit(c, 3))?;
181                        self.mill_count += 1;
182                        Ok(words)
183                    })?;
184                }
185                let num = sub(&TWO_DIGITS_WORD, &num, Some(1), |c| {
186                    Ok(format!(
187                        "{}, ",
188                        tenfn(digit(c, 1), digit(c, 2), self.mill_count)?
189                    ))
190                })?;
191                sub(&ONE_DIGIT_WORD, &num, Some(1), |c| {
192                    Ok(format!("{}, ", unitfn(digit(c, 1), self.mill_count)?))
193                })
194            }
195        }
196    }
197}
198
199fn render(chunks: &[String], decimal: Option<&str>, comma: &str) -> String {
200    let Some((first_item, rest)) = chunks.split_first() else {
201        return String::new();
202    };
203    let mut out = first_item.clone();
204    let mut first = decimal.is_none_or(|d| !first_item.ends_with(d));
205    for chunk in rest {
206        if Some(chunk.as_str()) == decimal {
207            first = false;
208        } else if first {
209            out.push_str(comma);
210        }
211        out.push(' ');
212        out.push_str(chunk);
213    }
214    out
215}
216
217enum Spelled {
218    Threshold(String),
219    Chunks {
220        sign: &'static str,
221        chunks: Vec<String>,
222    },
223}
224
225impl Engine {
226    /// Returns the ordinal of a number ("1" -> "1st") or of a number word
227    /// ("one" -> "first").
228    pub fn ordinal(&self, num: impl Display) -> String {
229        let num = num.to_string();
230        if !num.starts_with(|c: char| c.is_ascii_digit()) {
231            return sub_ord(&num);
232        }
233        let n = if !num.contains('.') {
234            last_two_digits(&num)
235        } else if num.ends_with(|c: char| c.is_ascii_digit()) {
236            last_two_digits(crate::text::tail(&num, 1))
237        } else {
238            last_two_digits(chop(&num, 1))
239        };
240        let suffix = nth(n % 100).or_else(|| nth(n % 10)).unwrap_or("th");
241        format!("{num}{suffix}")
242    }
243
244    /// Returns a number in words: 1234 -> "one thousand, two hundred and thirty-four".
245    pub fn number_to_words(&self, num: impl Display) -> Result<String, Error> {
246        self.number_to_words_with(num, &NumberToWordsOptions::default())
247    }
248
249    pub fn number_to_words_with(
250        &self,
251        num: impl Display,
252        options: &NumberToWordsOptions,
253    ) -> Result<String, Error> {
254        Ok(match spell(&num.to_string(), options)? {
255            Spelled::Threshold(s) => s,
256            Spelled::Chunks { sign, chunks } => {
257                let value = if options.group > 0 {
258                    chunks.join(", ")
259                } else {
260                    render(&chunks, options.decimal.as_deref(), &options.comma)
261                };
262                if sign.is_empty() {
263                    value
264                } else {
265                    format!("{sign} {value}")
266                }
267            }
268        })
269    }
270
271    /// Like [`number_to_words_with`](Self::number_to_words_with), returning
272    /// the separate chunks ("one thousand", "two hundred and thirty-four").
273    pub fn number_to_words_list(
274        &self,
275        num: impl Display,
276        options: &NumberToWordsOptions,
277    ) -> Result<Vec<String>, Error> {
278        Ok(match spell(&num.to_string(), options)? {
279            Spelled::Threshold(s) => vec![s],
280            Spelled::Chunks { sign, chunks } => {
281                let sign = (!sign.is_empty()).then(|| sign.to_string());
282                sign.into_iter().chain(chunks).collect()
283            }
284        })
285    }
286}
287
288fn spell(num: &str, options: &NumberToWordsOptions) -> Result<Spelled, Error> {
289    let bad_value = || Error::BadNumValue(num.to_string());
290
291    if let Some(threshold) = options.threshold {
292        let value: f64 = num.trim().parse().map_err(|_| bad_value())?;
293        if value > threshold as f64 {
294            let mut parts = num.splitn(2, '.');
295            let mut whole = parts.next().unwrap_or_default().to_string();
296            while !options.comma.is_empty() && FOUR_DIGIT_COMMA.is_match(&whole).unwrap_or(false) {
297                whole = FOUR_DIGIT_COMMA
298                    .replace_all(&whole, "${1},${2}")
299                    .into_owned();
300            }
301            return Ok(Spelled::Threshold(match parts.next() {
302                Some(fraction) => format!("{whole}.{fraction}"),
303                None => whole,
304            }));
305        }
306    }
307
308    if options.group > 3 {
309        return Err(Error::BadChunkingOption);
310    }
311    let group = options.group;
312
313    let sign = match num.trim_start().chars().next() {
314        Some('+') => "plus",
315        Some('-') => "minus",
316        Some(_) => "",
317        None => return Err(bad_value()),
318    };
319
320    let mut num = num.to_string();
321    if NTH_SUFF.contains(&num.as_str()) {
322        num = options.zero.clone();
323    }
324    let myord = NTH_SUFF.contains(&crate::text::tail(&num, 2));
325    if myord {
326        num = chop(&num, 2).to_string();
327    }
328
329    let decimal = options.decimal.as_deref().filter(|d| !d.is_empty());
330    let mut chunks: Vec<String> = match decimal {
331        Some(_) if group == 0 => num.splitn(2, '.').map(String::from).collect(),
332        Some(_) => num.split('.').map(String::from).collect(),
333        None => vec![num],
334    };
335    let finalpoint = chunks.last().is_some_and(|c| c.is_empty());
336    if finalpoint {
337        chunks.pop();
338    }
339
340    let loopstart = chunks.first().is_some_and(|c| c.is_empty());
341    let mut first = Some(!loopstart);
342    let mut words = Words {
343        andword: &options.andword,
344        zero: &options.zero,
345        one: &options.one,
346        mill_count: 0,
347    };
348    for chunk in chunks.iter_mut().skip(usize::from(loopstart)) {
349        let mut digits = NON_DIGIT.replace_all(chunk, "").into_owned();
350        if digits.is_empty() {
351            digits = "0".to_string();
352        }
353        let is_first = first == Some(true);
354        let mut text = if group == 0 && !is_first {
355            words.enword(&digits, 1)?
356        } else {
357            words.enword(&digits, group)?
358        };
359        if let Some(stripped) = text.strip_suffix(", ") {
360            text = stripped.to_string();
361        }
362        text = WHITESPACES_COMMA.replace_all(&text, ",").into_owned();
363        if group == 0 && is_first {
364            text = sub(&COMMA_WORD, &text, None, |c| {
365                Ok(format!(" {} {}", options.andword, crate::text::group(c, 1)))
366            })?;
367        }
368        text = WHITESPACES.replace_all(&text, " ").trim().to_string();
369        if is_first {
370            first = None;
371        }
372        *chunk = text;
373    }
374
375    let separator = format!("{} ", options.comma);
376    let mut numchunks: Vec<String> = Vec::new();
377    if first != Some(false) {
378        numchunks.extend(chunks[0].split(&separator).map(String::from));
379    }
380    if myord {
381        if let Some(last) = numchunks.last_mut() {
382            *last = sub_ord(last);
383        }
384    }
385    let decimal = options.decimal.clone().unwrap_or_default();
386    for chunk in chunks.iter().skip(1) {
387        numchunks.push(decimal.clone());
388        numchunks.extend(chunk.split(&separator).map(String::from));
389    }
390    if finalpoint {
391        numchunks.push(decimal);
392    }
393
394    Ok(Spelled::Chunks {
395        sign,
396        chunks: numchunks,
397    })
398}
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn ordinal_suffixes() {
406        assert_eq!(sub_ord("one"), "first");
407        assert_eq!(sub_ord("twenty"), "twentieth");
408        assert_eq!(sub_ord("four"), "fourth");
409        assert_eq!(last_two_digits("123456"), 56);
410    }
411
412    #[test]
413    fn tens() {
414        assert_eq!(tenfn(2, 1, 0).unwrap(), "twenty-one ");
415        assert_eq!(tenfn(1, 3, 1).unwrap(), "thirteen thousand");
416        assert_eq!(tenfn(0, 0, 12), Err(Error::NumOutOfRange));
417    }
418}