1use crate::{format_decimal_in, format_percent_in};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct NumberFormat {
15 percent: bool,
16 fraction_digits: usize,
17}
18
19impl NumberFormat {
20 pub const fn decimal() -> Self {
22 Self {
23 percent: false,
24 fraction_digits: 2,
25 }
26 }
27
28 pub const fn percent() -> Self {
30 Self {
31 percent: true,
32 fraction_digits: 0,
33 }
34 }
35
36 #[must_use]
38 pub const fn fraction_digits(mut self, digits: usize) -> Self {
39 self.fraction_digits = if digits > 20 { 20 } else { digits };
40 self
41 }
42
43 #[must_use]
45 pub fn format(self, value: f64) -> String {
46 self.format_in(&crate::locale().get(), value)
47 }
48
49 #[must_use]
51 pub fn format_in(self, locale: &str, value: f64) -> String {
52 if self.percent {
53 format_percent_in(locale, value, self.fraction_digits)
54 } else {
55 format_decimal_in(locale, value, self.fraction_digits)
56 }
57 }
58
59 #[must_use]
61 pub fn parse(self, text: &str) -> Option<f64> {
62 self.parse_in(&crate::locale().get(), text)
63 }
64
65 #[must_use]
67 pub fn parse_in(self, locale: &str, text: &str) -> Option<f64> {
68 let digits: Vec<char> = (0..10)
70 .map(|i| {
71 format_decimal_in(locale, f64::from(i), 0)
72 .chars()
73 .find(|c| !bidi(*c))
74 .unwrap_or('0')
75 })
76 .collect();
77 let decimal = format_decimal_in(locale, 1.1, 1)
78 .chars()
79 .find(|c| !bidi(*c) && !digits.contains(c))?;
80 let group = format_decimal_in(locale, 123_456_789.0, 0)
81 .chars()
82 .find(|c| !bidi(*c) && !digits.contains(c));
83 let cleaned: String = text.chars().filter(|c| !bidi(*c)).collect();
84 let mut text = cleaned.trim();
85 if self.percent {
86 if text.starts_with(['%', '\u{066a}']) {
88 text = text[text.chars().next()?.len_utf8()..].trim();
89 } else if text.ends_with(['%', '\u{066a}']) {
90 text = text[..text.len() - text.chars().last()?.len_utf8()].trim();
91 }
92 }
93 let negative = text.starts_with(['-', '\u{2212}']);
94 if negative || text.starts_with('+') {
95 text = &text[text.chars().next()?.len_utf8()..];
96 }
97 let mut ascii = String::new();
98 let mut grouped_integer = String::new();
99 let mut had_group = false;
100 let mut fraction = false;
101 for c in text.chars() {
102 if let Some(d) = digits
103 .iter()
104 .position(|d| *d == c)
105 .or_else(|| c.is_ascii_digit().then(|| (c as u8 - b'0') as usize))
106 {
107 let d = char::from(b'0' + d as u8);
108 ascii.push(d);
109 if !fraction {
110 grouped_integer.push(d);
111 }
112 } else if c == decimal && !fraction {
113 ascii.push('.');
114 fraction = true;
115 } else if group.is_some_and(|g| c == g || (g.is_whitespace() && c.is_whitespace()))
116 && !fraction
117 {
118 grouped_integer.push(',');
119 had_group = true;
120 } else {
121 return None;
122 }
123 }
124 if ascii.is_empty() || ascii.ends_with('.') {
125 return None;
126 }
127 let mut value: f64 = ascii.parse().ok()?;
128 if !value.is_finite() {
129 return None;
130 }
131 if had_group {
132 let integer = ascii.split('.').next()?.parse::<f64>().ok()?;
133 let expected: String = format_decimal_in(locale, integer, 0)
134 .chars()
135 .filter(|c| !bidi(*c))
136 .map(|c| {
137 digits
138 .iter()
139 .position(|d| *d == c)
140 .map_or(',', |i| char::from(b'0' + i as u8))
141 })
142 .collect();
143 if grouped_integer != expected {
144 return None;
145 }
146 }
147 if negative {
148 value = -value;
149 }
150 if self.percent {
151 value /= 100.0;
152 }
153 Some(value)
154 }
155}
156
157fn bidi(c: char) -> bool {
158 matches!(
159 c,
160 '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{2066}'..='\u{2069}'
161 )
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167
168 #[test]
169 fn displayed_numbers_round_trip_across_locales_and_numbering_systems() {
170 for locale in [
171 "en-US",
172 "fr",
173 "de",
174 "de-CH",
175 "hi-IN",
176 "ar-EG",
177 "fa",
178 "ja",
179 "ko",
180 "zh-CN",
181 "tr",
182 "en-u-nu-arab",
183 ] {
184 for format in [
185 NumberFormat::decimal(),
186 NumberFormat::percent().fraction_digits(2),
187 ] {
188 for value in [0.0, 0.4, -12.5, 1_234_567.25] {
189 let text = format.format_in(locale, value);
190 assert_eq!(
191 format.parse_in(locale, &text),
192 Some(value),
193 "{locale}: {text}"
194 );
195 }
196 }
197 }
198 }
199
200 #[test]
201 fn edits_respect_locale_and_reject_ambiguous_or_incomplete_input() {
202 let decimal = NumberFormat::decimal();
203 assert_eq!(decimal.parse_in("de", "1.234,5"), Some(1234.5));
204 assert_eq!(decimal.parse_in("fr", "1 234,5"), Some(1234.5));
205 assert_eq!(decimal.parse_in("ar-EG", "١٢٫٥"), Some(12.5));
206 assert_eq!(decimal.parse_in("ar-EG", "12٫5"), Some(12.5));
207 assert_eq!(decimal.parse_in("hi-IN", "12,34,567.5"), Some(1_234_567.5));
208 assert_eq!(decimal.parse_in("en", ".5"), Some(0.5));
209 for text in [
210 "",
211 "-",
212 "1.",
213 "1,2",
214 "1,,234",
215 "12,34,567",
216 "NaN",
217 "inf",
218 "1e3",
219 "12%",
220 "1 234",
221 "--2",
222 ] {
223 assert_eq!(decimal.parse_in("en", text), None, "{text}");
224 }
225 assert_eq!(decimal.parse_in("de", "1.5"), None);
226 let percent = NumberFormat::percent();
227 assert_eq!(percent.parse_in("en", "40"), Some(0.4));
228 assert_eq!(percent.parse_in("de", "40,5 %"), Some(0.405));
229 assert_eq!(percent.parse_in("ar-EG", "\u{2068}٤٠٪\u{2069}"), Some(0.4));
230 assert_eq!(percent.parse_in("en", "%40%"), None);
231 }
232}