Skip to main content

mln_expression/
number_format.rs

1// Ports include/mln/style/expression/number_format.hpp and
2// src/mln/style/expression/number_format.cpp.
3
4use crate::expression::{
5    EvaluationContext, EvaluationResult, Expression, ExpressionBase, Kind, downcast,
6};
7use crate::parsing_context::{ParseResult, ParsingContext};
8use crate::type_::{self, Type};
9use crate::value::{Value, to_string};
10use maplibre_native_base::{Value as MbglValue, ValueObject};
11use mln_conversion::Convertible;
12
13const LOCALE_KEY: &str = "locale";
14const CURRENCY_KEY: &str = "currency";
15const MIN_FRACTION_DIGITS_KEY: &str = "min-fraction-digits";
16const MAX_FRACTION_DIGITS_KEY: &str = "max-fraction-digits";
17
18/// `platform::formatNumber` (platform/default/src/mln/i18n/number_format.cpp,
19/// ICU `NumberFormatter`).
20// TODO(port): ICU number formatting. This implements ICU's behaviour for the
21// root/en locales only: the shortest round-trip decimal of the double, rounded
22// half-even to maxFractionDigits and padded to minFractionDigits, ',' grouping
23// and '.' decimal separator; with a currency, ICU's currency precision and an
24// en-US symbol for a few common currencies. The locale is ignored (see
25// DEVIATIONS.md).
26fn format_number(
27    number: f64,
28    _locale_id: &str,
29    currency: &str,
30    min_fraction_digits: u8,
31    max_fraction_digits: u8,
32) -> String {
33    if number.is_nan() {
34        return "NaN".to_owned();
35    }
36    if number.is_infinite() {
37        return if number > 0.0 { "∞" } else { "-∞" }.to_owned();
38    }
39
40    let (symbol, min_fraction, max_fraction) = if currency.is_empty() {
41        (None, min_fraction_digits as usize, max_fraction_digits as usize)
42    } else {
43        let digits = match currency {
44            "JPY" | "KRW" | "VND" | "CLP" | "ISK" | "UGX" | "PYG" => 0,
45            _ => 2,
46        };
47        let symbol = match currency {
48            "USD" => "$".to_owned(),
49            "EUR" => "€".to_owned(),
50            "JPY" => "¥".to_owned(),
51            "GBP" => "£".to_owned(),
52            "CNY" => "CN¥".to_owned(),
53            "INR" => "₹".to_owned(),
54            "KRW" => "₩".to_owned(),
55            "CAD" => "CA$".to_owned(),
56            "AUD" => "A$".to_owned(),
57            other => format!("{other}\u{a0}"),
58        };
59        (Some(symbol), digits, digits)
60    };
61    let max_fraction = max_fraction.max(min_fraction);
62
63    // Shortest round-trip digits of |number| (`digits` is 0.d0d1d2... *
64    // 10^point, so the decimal point sits after index `point`).
65    let (mut digits, mut point) = shortest_digits(number.abs());
66    if digits.iter().all(|d| *d == 0) {
67        digits = vec![0];
68        point = 1;
69    }
70
71    // Round half-even at max_fraction fraction digits.
72    let keep = point + max_fraction as i64;
73    if keep < digits.len() as i64 {
74        let (head_len, round_up) = if keep < 0 {
75            (0usize, false)
76        } else {
77            let keep = keep as usize;
78            let first = digits[keep];
79            let rest_nonzero = digits[keep + 1..].iter().any(|d| *d != 0);
80            let last_kept_odd = keep > 0 && digits[keep - 1] % 2 == 1;
81            (keep, first > 5 || (first == 5 && (rest_nonzero || last_kept_odd)))
82        };
83        digits.truncate(head_len);
84        if round_up {
85            let mut i = digits.len();
86            loop {
87                if i == 0 {
88                    digits.insert(0, 1);
89                    point += 1;
90                    break;
91                }
92                i -= 1;
93                if digits[i] == 9 {
94                    digits[i] = 0;
95                } else {
96                    digits[i] += 1;
97                    break;
98                }
99            }
100        }
101    }
102
103    // Integer and fraction digit strings.
104    let digit_at = |i: i64| -> u8 {
105        if i >= 0 && (i as usize) < digits.len() { digits[i as usize] } else { 0 }
106    };
107    let mut int_part = String::new();
108    if point <= 0 {
109        int_part.push('0');
110    } else {
111        for i in 0..point {
112            int_part.push((b'0' + digit_at(i)) as char);
113        }
114    }
115    let mut frac_part = String::new();
116    for i in 0..max_fraction as i64 {
117        frac_part.push((b'0' + digit_at(point + i)) as char);
118    }
119    while frac_part.len() > min_fraction && frac_part.ends_with('0') {
120        frac_part.pop();
121    }
122
123    let mut grouped = String::new();
124    let int_len = int_part.len();
125    for (i, c) in int_part.chars().enumerate() {
126        if i > 0 && (int_len - i) % 3 == 0 {
127            grouped.push(',');
128        }
129        grouped.push(c);
130    }
131    // ICU keeps the sign of negative numbers that round to zero, and of -0.
132    let mut result = String::new();
133    if number.is_sign_negative() {
134        result.push('-');
135    }
136    if let Some(symbol) = symbol {
137        result.push_str(&symbol);
138    }
139    result.push_str(&grouped);
140    if !frac_part.is_empty() {
141        result.push('.');
142        result.push_str(&frac_part);
143    }
144    result
145}
146
147
148/// Digits and decimal point position of a `{:e}` formatting.
149fn sci_digits(sci: &str) -> (Vec<u8>, i64) {
150    let (mantissa, exponent) = sci.split_once('e').unwrap();
151    let exponent: i64 = exponent.parse().unwrap();
152    let digits = mantissa.bytes().filter(|b| b.is_ascii_digit()).map(|b| b - b'0').collect();
153    (digits, exponent + 1)
154}
155
156/// The shortest round-trip decimal digits of `x`, as double-conversion's
157/// SHORTEST mode (which ICU's DecimalQuantity uses) produces them: when two
158/// shortest candidates are exactly equally close, the even one (Rust's
159/// formatter may pick the other).
160fn shortest_digits(x: f64) -> (Vec<u8>, i64) {
161    let (digits, point) = sci_digits(&format!("{x:e}"));
162    let (mut exact, exact_point) = sci_digits(&format!("{x:.1100e}"));
163    while exact.len() > 1 && exact.last() == Some(&0) {
164        exact.pop();
165    }
166    let l = digits.len();
167    if exact_point == point && exact.len() == l + 1 && exact[l] == 5 && l <= 17 {
168        let to_int = |d: &[u8]| d.iter().fold(0u64, |a, d| a * 10 + *d as u64);
169        let low = to_int(&exact[..l]);
170        let shortest = to_int(&digits);
171        if shortest == low || shortest == low + 1 {
172            let even = if low % 2 == 0 { low } else { low + 1 };
173            let mut out: Vec<u8> = even.to_string().bytes().map(|b| b - b'0').collect();
174            let mut p = point;
175            if out.len() > l {
176                p += 1;
177            }
178            while out.len() < l {
179                out.insert(0, 0);
180            }
181            while out.len() > 1 && out.last() == Some(&0) {
182                out.pop();
183            }
184            return (out, p);
185        }
186    }
187    (digits, point)
188}
189
190pub struct NumberFormat {
191    base: ExpressionBase,
192    number: Box<dyn Expression>,
193    locale: Option<Box<dyn Expression>>,
194    currency: Option<Box<dyn Expression>>,
195    min_fraction_digits: Option<Box<dyn Expression>>,
196    max_fraction_digits: Option<Box<dyn Expression>>,
197}
198
199fn opt_deps(e: &Option<Box<dyn Expression>>) -> crate::expression::Dependency {
200    e.as_ref().map_or(Default::default(), |e| e.dependencies())
201}
202
203fn opt_equal(l: &Option<Box<dyn Expression>>, r: &Option<Box<dyn Expression>>) -> bool {
204    match (l, r) {
205        (Some(l), Some(r)) => l.equals(&**r),
206        (None, None) => true,
207        _ => false,
208    }
209}
210
211/// `static_cast<uint8_t>(double)`: through int32 on x86-64.
212fn static_cast_u8(d: f64) -> u8 {
213    (if d > -2147483649.0 && d < 2147483648.0 { d as i32 } else { i32::MIN }) as u8
214}
215
216impl NumberFormat {
217    pub fn new(
218        number: Box<dyn Expression>,
219        locale: Option<Box<dyn Expression>>,
220        currency: Option<Box<dyn Expression>>,
221        min_fraction_digits: Option<Box<dyn Expression>>,
222        max_fraction_digits: Option<Box<dyn Expression>>,
223    ) -> Self {
224        let deps = number.dependencies()
225            | opt_deps(&locale)
226            | opt_deps(&currency)
227            | opt_deps(&min_fraction_digits)
228            | opt_deps(&max_fraction_digits);
229        NumberFormat {
230            base: ExpressionBase::new(Kind::NumberFormat, Type::String, deps),
231            number,
232            locale,
233            currency,
234            min_fraction_digits,
235            max_fraction_digits,
236        }
237    }
238
239    pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
240        let length = value.array_length();
241
242        if length != 3 {
243            ctx.error(format!("Expected two arguments, but found {length} instead."));
244            return None;
245        }
246
247        let Some(number_result) = ctx.parse(&value.array_member(1), 1, Some(Type::Number), None) else {
248            ctx.error("Failed to parse the number.".to_owned());
249            return None;
250        };
251
252        let t = number_result.get_type();
253        if *t != Type::Number {
254            ctx.error(format!(
255                "Expected argument of type number, but found {} instead.",
256                type_::to_string(t)
257            ));
258            return None;
259        }
260
261        let options = value.array_member(2);
262        if !options.is_object() {
263            ctx.error("Number-format options argument must be an object.".to_owned());
264            return None;
265        }
266
267        let mut parse_option = |key: &str, t: Type, message: &str| -> Result<Option<Box<dyn Expression>>, ()> {
268            if let Some(option) = options.object_member(key) {
269                match ctx.parse(&option, 1, Some(t), None) {
270                    Some(r) => Ok(Some(r)),
271                    None => {
272                        ctx.error(message.to_owned());
273                        Err(())
274                    }
275                }
276            } else {
277                Ok(None)
278            }
279        };
280
281        let locale_result = parse_option(LOCALE_KEY, Type::String, "Number-format locale parsing failed.").ok()?;
282        let currency_result =
283            parse_option(CURRENCY_KEY, Type::String, "Number-format currency parsing failed.").ok()?;
284        let min_fraction_digits_result = parse_option(
285            MIN_FRACTION_DIGITS_KEY,
286            Type::Number,
287            "Number-format min-fraction-digits parsing failed.",
288        )
289        .ok()?;
290        let max_fraction_digits_result = parse_option(
291            MAX_FRACTION_DIGITS_KEY,
292            Type::Number,
293            "Number-format max-fraction-digits parsing failed.",
294        )
295        .ok()?;
296
297        Some(Box::new(NumberFormat::new(
298            number_result,
299            locale_result,
300            currency_result,
301            min_fraction_digits_result,
302            max_fraction_digits_result,
303        )))
304    }
305}
306
307impl Expression for NumberFormat {
308    fn base(&self) -> &ExpressionBase {
309        &self.base
310    }
311
312    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
313        let number_result = self.number.evaluate(params)?;
314        let evaluated_number = number_result.as_number().expect("numeric input");
315
316        let mut evaluated_locale = String::new();
317        if let Some(locale) = &self.locale {
318            evaluated_locale = to_string(&locale.evaluate(params)?);
319        }
320
321        let mut evaluated_currency = String::new();
322        if let Some(currency) = &self.currency {
323            evaluated_currency = to_string(&currency.evaluate(params)?);
324        }
325
326        let mut evaluated_min_fraction_digits: u8 = 0;
327        if let Some(min) = &self.min_fraction_digits {
328            evaluated_min_fraction_digits = static_cast_u8(min.evaluate(params)?.as_number().expect("number"));
329        }
330
331        let mut evaluated_max_fraction_digits: u8 = 3;
332        if let Some(max) = &self.max_fraction_digits {
333            evaluated_max_fraction_digits = static_cast_u8(max.evaluate(params)?.as_number().expect("number"));
334        }
335
336        Ok(Value::String(format_number(
337            evaluated_number,
338            &evaluated_locale,
339            &evaluated_currency,
340            evaluated_min_fraction_digits,
341            evaluated_max_fraction_digits,
342        )))
343    }
344
345    fn each_child<'a>(&'a self, visit: &mut dyn FnMut(&'a dyn Expression)) {
346        visit(&*self.number);
347        for e in [&self.locale, &self.currency, &self.min_fraction_digits, &self.max_fraction_digits]
348            .into_iter()
349            .flatten()
350        {
351            visit(&**e);
352        }
353    }
354
355    fn equals(&self, e: &dyn Expression) -> bool {
356        if e.get_kind() == Kind::NumberFormat {
357            let rhs = downcast::<NumberFormat>(e).expect("NumberFormat");
358            return opt_equal(&self.locale, &rhs.locale)
359                && opt_equal(&self.currency, &rhs.currency)
360                && opt_equal(&self.min_fraction_digits, &rhs.min_fraction_digits)
361                && opt_equal(&self.max_fraction_digits, &rhs.max_fraction_digits)
362                && self.number.equals(&*rhs.number);
363        }
364        false
365    }
366
367    fn possible_outputs(&self) -> Vec<Option<Value>> {
368        vec![None]
369    }
370
371    fn serialize(&self) -> MbglValue {
372        let mut options = ValueObject::new();
373        if let Some(locale) = &self.locale {
374            options.insert(LOCALE_KEY.to_owned(), locale.serialize());
375        }
376        if let Some(currency) = &self.currency {
377            options.insert(CURRENCY_KEY.to_owned(), currency.serialize());
378        }
379        if let Some(min) = &self.min_fraction_digits {
380            options.insert(MIN_FRACTION_DIGITS_KEY.to_owned(), min.serialize());
381        }
382        if let Some(max) = &self.max_fraction_digits {
383            options.insert(MAX_FRACTION_DIGITS_KEY.to_owned(), max.serialize());
384        }
385        MbglValue::Array(vec![
386            MbglValue::String(self.get_operator()),
387            self.number.serialize(),
388            MbglValue::Object(options),
389        ])
390    }
391
392    fn get_operator(&self) -> String {
393        "number-format".to_owned()
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use super::format_number;
400
401    #[test]
402    fn icu_like() {
403        assert_eq!(format_number(123456.789, "", "", 0, 3), "123,456.789");
404        assert_eq!(format_number(123456.789, "en-US", "JPY", 0, 3), "¥123,457");
405        assert_eq!(format_number(123456.789, "en-US", "EUR", 0, 3), "€123,456.79");
406        assert_eq!(format_number(987654321.234567, "en-US", "", 15, 20), "987,654,321.234567000000000");
407        assert_eq!(format_number(987654321.234567, "en-US", "", 2, 4), "987,654,321.2346");
408        assert_eq!(format_number(0.5, "", "", 0, 0), "0");
409        assert_eq!(format_number(1.5, "", "", 0, 0), "2");
410        assert_eq!(format_number(0.0005, "", "", 0, 3), "0");
411    }
412}