Skip to main content

day_localization/
number.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Matching locale-aware display and parsing for editable numbers.
5
6use crate::{format_decimal_in, format_percent_in};
7
8/// A decimal or percentage format shared by numeric controls and readouts.
9///
10/// Parsing uses the current locale's decimal separator and digits; ASCII digits are also
11/// accepted. Grouped input must match the locale's grouping. Percent input may omit its sign:
12/// `40` and `40%` both mean `0.4`. Scientific notation, currency and units are not accepted.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct NumberFormat {
15    percent: bool,
16    fraction_digits: usize,
17}
18
19impl NumberFormat {
20    /// Decimal notation with two fraction digits.
21    pub const fn decimal() -> Self {
22        Self {
23            percent: false,
24            fraction_digits: 2,
25        }
26    }
27
28    /// Percentage notation with no fraction digits; `0.4` displays as `40%` in English.
29    pub const fn percent() -> Self {
30        Self {
31            percent: true,
32            fraction_digits: 0,
33        }
34    }
35
36    /// Display this many fraction digits (at most 20). Parsing retains entered precision.
37    pub const fn fraction_digits(mut self, digits: usize) -> Self {
38        self.fraction_digits = if digits > 20 { 20 } else { digits };
39        self
40    }
41
42    /// Format using the current locale, tracking locale changes in reactive closures.
43    pub fn format(self, value: f64) -> String {
44        self.format_in(&crate::locale().get(), value)
45    }
46
47    /// Format in an explicit locale without subscribing to locale changes.
48    pub fn format_in(self, locale: &str, value: f64) -> String {
49        if self.percent {
50            format_percent_in(locale, value, self.fraction_digits)
51        } else {
52            format_decimal_in(locale, value, self.fraction_digits)
53        }
54    }
55
56    /// Parse a complete edit in the current locale. Invalid or unfinished edits return `None`.
57    pub fn parse(self, text: &str) -> Option<f64> {
58        self.parse_in(&crate::locale().get(), text)
59    }
60
61    /// Parse in an explicit locale. Grouping is validated rather than silently discarded.
62    pub fn parse_in(self, locale: &str, text: &str) -> Option<f64> {
63        // Use the same ICU data as display, including Unicode numbering-system extensions.
64        let digits: Vec<char> = (0..10)
65            .map(|i| {
66                format_decimal_in(locale, i as f64, 0)
67                    .chars()
68                    .find(|c| !bidi(*c))
69                    .unwrap_or('0')
70            })
71            .collect();
72        let decimal = format_decimal_in(locale, 1.1, 1)
73            .chars()
74            .find(|c| !bidi(*c) && !digits.contains(c))?;
75        let group = format_decimal_in(locale, 123456789.0, 0)
76            .chars()
77            .find(|c| !bidi(*c) && !digits.contains(c));
78        let cleaned: String = text.chars().filter(|c| !bidi(*c)).collect();
79        let mut text = cleaned.trim();
80        if self.percent {
81            // Accept a pasted locale percent sign or its ASCII keyboard equivalent at either end.
82            if text.starts_with(['%', '\u{066a}']) {
83                text = text[text.chars().next()?.len_utf8()..].trim();
84            } else if text.ends_with(['%', '\u{066a}']) {
85                text = text[..text.len() - text.chars().last()?.len_utf8()].trim();
86            }
87        }
88        let negative = text.starts_with(['-', '\u{2212}']);
89        if negative || text.starts_with('+') {
90            text = &text[text.chars().next()?.len_utf8()..];
91        }
92        let mut ascii = String::new();
93        let mut grouped_integer = String::new();
94        let mut had_group = false;
95        let mut fraction = false;
96        for c in text.chars() {
97            if let Some(d) = digits
98                .iter()
99                .position(|d| *d == c)
100                .or_else(|| c.is_ascii_digit().then(|| (c as u8 - b'0') as usize))
101            {
102                let d = char::from(b'0' + d as u8);
103                ascii.push(d);
104                if !fraction {
105                    grouped_integer.push(d);
106                }
107            } else if c == decimal && !fraction {
108                ascii.push('.');
109                fraction = true;
110            } else if group.is_some_and(|g| c == g || (g.is_whitespace() && c.is_whitespace()))
111                && !fraction
112            {
113                grouped_integer.push(',');
114                had_group = true;
115            } else {
116                return None;
117            }
118        }
119        if ascii.is_empty() || ascii.ends_with('.') {
120            return None;
121        }
122        let mut value: f64 = ascii.parse().ok()?;
123        if !value.is_finite() {
124            return None;
125        }
126        if had_group {
127            let integer = ascii.split('.').next()?.parse::<f64>().ok()?;
128            let expected: String = format_decimal_in(locale, integer, 0)
129                .chars()
130                .filter(|c| !bidi(*c))
131                .map(|c| {
132                    digits
133                        .iter()
134                        .position(|d| *d == c)
135                        .map_or(',', |i| char::from(b'0' + i as u8))
136                })
137                .collect();
138            if grouped_integer != expected {
139                return None;
140            }
141        }
142        if negative {
143            value = -value;
144        }
145        if self.percent {
146            value /= 100.0;
147        }
148        Some(value)
149    }
150}
151
152fn bidi(c: char) -> bool {
153    matches!(
154        c,
155        '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{2066}'..='\u{2069}'
156    )
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn displayed_numbers_round_trip_across_locales_and_numbering_systems() {
165        for locale in [
166            "en-US",
167            "fr",
168            "de",
169            "de-CH",
170            "hi-IN",
171            "ar-EG",
172            "fa",
173            "ja",
174            "ko",
175            "zh-CN",
176            "tr",
177            "en-u-nu-arab",
178        ] {
179            for format in [
180                NumberFormat::decimal(),
181                NumberFormat::percent().fraction_digits(2),
182            ] {
183                for value in [0.0, 0.4, -12.5, 1234567.25] {
184                    let text = format.format_in(locale, value);
185                    assert_eq!(
186                        format.parse_in(locale, &text),
187                        Some(value),
188                        "{locale}: {text}"
189                    );
190                }
191            }
192        }
193    }
194
195    #[test]
196    fn edits_respect_locale_and_reject_ambiguous_or_incomplete_input() {
197        let decimal = NumberFormat::decimal();
198        assert_eq!(decimal.parse_in("de", "1.234,5"), Some(1234.5));
199        assert_eq!(decimal.parse_in("fr", "1 234,5"), Some(1234.5));
200        assert_eq!(decimal.parse_in("ar-EG", "١٢٫٥"), Some(12.5));
201        assert_eq!(decimal.parse_in("ar-EG", "12٫5"), Some(12.5));
202        assert_eq!(decimal.parse_in("hi-IN", "12,34,567.5"), Some(1234567.5));
203        assert_eq!(decimal.parse_in("en", ".5"), Some(0.5));
204        for text in [
205            "",
206            "-",
207            "1.",
208            "1,2",
209            "1,,234",
210            "12,34,567",
211            "NaN",
212            "inf",
213            "1e3",
214            "12%",
215            "1 234",
216            "--2",
217        ] {
218            assert_eq!(decimal.parse_in("en", text), None, "{text}");
219        }
220        assert_eq!(decimal.parse_in("de", "1.5"), None);
221        let percent = NumberFormat::percent();
222        assert_eq!(percent.parse_in("en", "40"), Some(0.4));
223        assert_eq!(percent.parse_in("de", "40,5 %"), Some(0.405));
224        assert_eq!(percent.parse_in("ar-EG", "\u{2068}٤٠٪\u{2069}"), Some(0.4));
225        assert_eq!(percent.parse_in("en", "%40%"), None);
226    }
227}