Skip to main content

ftui_i18n/format/
number.rs

1#![forbid(unsafe_code)]
2
3//! Locale-aware number, currency, and percentage formatting.
4
5use super::data::{
6    CurrencyPlacement, LocaleData, NumberSymbols, PercentPlacement, lookup_locale_data,
7};
8use super::error::FormattingError;
9
10/// Rounding strategy for numeric formatting.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12pub enum RoundingMode {
13    /// Round half away from zero (standard commercial / school rounding).
14    #[default]
15    HalfUp,
16    /// Round half to nearest even digit (banker's rounding).
17    HalfEven,
18    /// Round towards zero (truncate).
19    Truncate,
20    /// Round towards negative infinity (floor).
21    Floor,
22    /// Round towards positive infinity (ceil).
23    Ceil,
24}
25
26/// Numerical display style.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub enum NumberStyle {
29    /// Standard decimal format (e.g. `1,234.56`).
30    #[default]
31    Decimal,
32    /// Percentage format multiplied by 100 with percent sign (e.g. `12.5%`).
33    Percent,
34    /// Currency format with symbol/code (e.g. `$1,234.56` or `1.234,56 €`).
35    Currency {
36        /// ISO 4217 code of the amount's currency (e.g. "USD", "EUR"), if not
37        /// the locale's own. Without a `symbol` it prints as the code, so `en`
38        /// shows EUR as `EUR 1,234.56`.
39        code: Option<&'static str>,
40        /// Symbol to print instead (e.g. "$", "€"). Takes precedence over `code`.
41        symbol: Option<&'static str>,
42    },
43}
44
45/// Digit numbering system.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub enum NumberingSystem {
48    /// Latin digits 0-9 (ASCII).
49    #[default]
50    Latn,
51    /// Eastern Arabic digits ٠-٩ (U+0660..=U+0669).
52    Arab,
53}
54
55/// Configuration for number formatting.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct NumberFormat {
58    /// Minimum number of integer digits (left-padded with zeros).
59    pub min_integer_digits: usize,
60    /// Minimum number of fractional digits (right-padded with zeros).
61    pub min_fraction_digits: usize,
62    /// Maximum number of fractional digits (rounded).
63    pub max_fraction_digits: usize,
64    /// Whether thousands / group separators should be inserted.
65    pub use_grouping: bool,
66    /// Rounding mode when truncating fractional digits.
67    pub rounding_mode: RoundingMode,
68    /// Display style (Decimal, Percent, Currency).
69    pub style: NumberStyle,
70    /// Numbering system / digit script.
71    pub numbering_system: NumberingSystem,
72    /// Whether non-finite floating point numbers (NaN, Inf) should be formatted
73    /// as symbols instead of returning `FormattingError::NonFinite`.
74    pub allow_non_finite: bool,
75}
76
77impl Default for NumberFormat {
78    fn default() -> Self {
79        Self {
80            min_integer_digits: 1,
81            min_fraction_digits: 0,
82            max_fraction_digits: 3,
83            use_grouping: true,
84            rounding_mode: RoundingMode::HalfUp,
85            style: NumberStyle::Decimal,
86            numbering_system: NumberingSystem::Latn,
87            allow_non_finite: false,
88        }
89    }
90}
91
92impl NumberFormat {
93    /// Create a new decimal number format configuration with default options.
94    #[must_use]
95    pub fn new() -> Self {
96        Self::default()
97    }
98
99    /// Set minimum integer digits.
100    #[must_use]
101    pub const fn min_integer_digits(mut self, digits: usize) -> Self {
102        self.min_integer_digits = digits;
103        self
104    }
105
106    /// Set fraction digit bounds.
107    #[must_use]
108    pub const fn fraction_digits(mut self, min: usize, max: usize) -> Self {
109        self.min_fraction_digits = min;
110        self.max_fraction_digits = max;
111        self
112    }
113
114    /// Set whether grouping separators are used.
115    #[must_use]
116    pub const fn use_grouping(mut self, grouping: bool) -> Self {
117        self.use_grouping = grouping;
118        self
119    }
120
121    /// Set the rounding mode.
122    #[must_use]
123    pub const fn rounding_mode(mut self, mode: RoundingMode) -> Self {
124        self.rounding_mode = mode;
125        self
126    }
127
128    /// Set the number style.
129    #[must_use]
130    pub const fn style(mut self, style: NumberStyle) -> Self {
131        self.style = style;
132        self
133    }
134
135    /// Set the numbering system.
136    #[must_use]
137    pub const fn numbering_system(mut self, system: NumberingSystem) -> Self {
138        self.numbering_system = system;
139        self
140    }
141
142    /// Set whether non-finite numbers (NaN, Inf) format to strings instead of erroring.
143    #[must_use]
144    pub const fn allow_non_finite(mut self, allow: bool) -> Self {
145        self.allow_non_finite = allow;
146        self
147    }
148}
149
150/// A locale-aware number formatter.
151#[derive(Debug, Clone)]
152pub struct NumberFormatter {
153    locale_tag: String,
154    symbols: NumberSymbols,
155    config: NumberFormat,
156}
157
158impl NumberFormatter {
159    /// Create a formatter for the given locale tag using default decimal options.
160    ///
161    /// # Errors
162    /// Returns `FormattingError::UnsupportedLocale` if the locale is not supported.
163    pub fn for_locale(locale: &str) -> Result<Self, FormattingError> {
164        Self::with_config(locale, NumberFormat::default())
165    }
166
167    /// Create a formatter with explicit configuration.
168    ///
169    /// # Errors
170    /// Returns `FormattingError::UnsupportedLocale` if the locale is not supported.
171    pub fn with_config(locale: &str, config: NumberFormat) -> Result<Self, FormattingError> {
172        let data = lookup_locale_data(locale)
173            .ok_or_else(|| FormattingError::UnsupportedLocale(locale.to_string()))?;
174        Ok(Self::from_data(data, config))
175    }
176
177    /// Create from pinned locale data directly.
178    #[must_use]
179    pub fn from_data(data: &'static LocaleData, config: NumberFormat) -> Self {
180        Self {
181            locale_tag: data.tag.to_string(),
182            symbols: data.number,
183            config,
184        }
185    }
186
187    /// Active locale tag.
188    #[must_use]
189    pub fn locale(&self) -> &str {
190        &self.locale_tag
191    }
192
193    /// Format an integer value according to the locale's conventions.
194    #[must_use]
195    pub fn format_int<I: Into<i128>>(&self, value: I) -> String {
196        let val = value.into();
197        let is_negative = val < 0;
198        let mut abs_val = val.unsigned_abs();
199        if matches!(self.config.style, NumberStyle::Percent) {
200            // `NumberStyle::Percent` is documented as "multiplied by 100", and
201            // `format_float` does multiply. Without this the same formatter
202            // rendered `12` as "12%" and `12.0` as "1,200%". Saturating rather
203            // than wrapping: a value within a factor of 100 of `i128::MAX` has
204            // no meaningful percentage, and this method cannot report an error.
205            abs_val = abs_val.saturating_mul(100);
206        }
207        let raw_digits = abs_val.to_string();
208
209        let padded_digits = if raw_digits.len() < self.config.min_integer_digits {
210            format!(
211                "{:0>width$}",
212                raw_digits,
213                width = self.config.min_integer_digits
214            )
215        } else {
216            raw_digits
217        };
218
219        let mut grouped = if self.config.use_grouping {
220            group_digits(
221                &padded_digits,
222                self.symbols.group_sep,
223                self.symbols.group_size,
224            )
225        } else {
226            padded_digits
227        };
228        // Every style, as in `format_float`: only Decimal padded, so a
229        // two-digit currency format printed `5` as `$5` here and `$5.00` there.
230        if self.config.min_fraction_digits > 0 {
231            grouped.push_str(self.symbols.decimal_sep);
232            grouped.extend(std::iter::repeat_n('0', self.config.min_fraction_digits));
233        }
234
235        let mut out = String::with_capacity(grouped.len() + 8);
236        if is_negative {
237            out.push_str(self.symbols.minus_sign);
238        }
239
240        match self.config.style {
241            NumberStyle::Decimal => {
242                out.push_str(&grouped);
243            }
244            NumberStyle::Percent => match self.symbols.percent_placement {
245                PercentPlacement::Prefix => {
246                    out.push_str(self.symbols.percent_sign);
247                    out.push_str(&grouped);
248                }
249                PercentPlacement::Suffix => {
250                    out.push_str(&grouped);
251                    out.push_str(self.symbols.percent_sign);
252                }
253                PercentPlacement::SuffixWithSpace => {
254                    out.push_str(&grouped);
255                    out.push(' ');
256                    out.push_str(self.symbols.percent_sign);
257                }
258            },
259            NumberStyle::Currency { code, symbol } => {
260                self.push_currency(&mut out, &grouped, code, symbol);
261            }
262        }
263
264        if self.config.numbering_system == NumberingSystem::Arab {
265            convert_to_arab_digits(&out)
266        } else {
267            out
268        }
269    }
270
271    /// Format a floating-point value according to the locale's conventions.
272    ///
273    /// # Errors
274    /// Returns `FormattingError::NonFinite` if the value is NaN or infinite and
275    /// `allow_non_finite` is false.
276    pub fn format_float(&self, value: f64) -> Result<String, FormattingError> {
277        if !value.is_finite() {
278            if !self.config.allow_non_finite {
279                return Err(FormattingError::NonFinite(value));
280            }
281            if value.is_nan() {
282                return Ok("NaN".to_string());
283            }
284            return if value.is_sign_negative() {
285                Ok(format!("{}∞", self.symbols.minus_sign))
286            } else {
287                Ok("∞".to_string())
288            };
289        }
290
291        // Percent moves the decimal point two places rather than computing
292        // `value * 100.0`, which rounds in binary (0.29 became
293        // 28.999999999999996) and overflows to infinity near `f64::MAX`.
294        let shift = if matches!(self.config.style, NumberStyle::Percent) {
295            2
296        } else {
297            0
298        };
299        let is_negative = value.is_sign_negative() && value != 0.0;
300
301        let (int_str, frac_str) = round_float_parts(
302            value.abs(),
303            shift,
304            self.config.max_fraction_digits,
305            self.config.min_fraction_digits,
306            self.config.rounding_mode,
307            is_negative,
308        );
309
310        let padded_int = if int_str.len() < self.config.min_integer_digits {
311            format!(
312                "{:0>width$}",
313                int_str,
314                width = self.config.min_integer_digits
315            )
316        } else {
317            int_str
318        };
319
320        let grouped_int = if self.config.use_grouping {
321            group_digits(&padded_int, self.symbols.group_sep, self.symbols.group_size)
322        } else {
323            padded_int
324        };
325
326        let mut num_str = String::with_capacity(grouped_int.len() + frac_str.len() + 4);
327        num_str.push_str(&grouped_int);
328        if !frac_str.is_empty() {
329            num_str.push_str(self.symbols.decimal_sep);
330            num_str.push_str(&frac_str);
331        }
332
333        let mut out = String::with_capacity(num_str.len() + 8);
334        if is_negative {
335            out.push_str(self.symbols.minus_sign);
336        }
337
338        match self.config.style {
339            NumberStyle::Decimal => {
340                out.push_str(&num_str);
341            }
342            NumberStyle::Percent => match self.symbols.percent_placement {
343                PercentPlacement::Prefix => {
344                    out.push_str(self.symbols.percent_sign);
345                    out.push_str(&num_str);
346                }
347                PercentPlacement::Suffix => {
348                    out.push_str(&num_str);
349                    out.push_str(self.symbols.percent_sign);
350                }
351                PercentPlacement::SuffixWithSpace => {
352                    out.push_str(&num_str);
353                    out.push(' ');
354                    out.push_str(self.symbols.percent_sign);
355                }
356            },
357            NumberStyle::Currency { code, symbol } => {
358                self.push_currency(&mut out, &num_str, code, symbol);
359            }
360        }
361
362        if self.config.numbering_system == NumberingSystem::Arab {
363            Ok(convert_to_arab_digits(&out))
364        } else {
365            Ok(out)
366        }
367    }
368
369    /// Append `number` marked as the currency the style names.
370    ///
371    /// `symbol` wins. Otherwise a `code` other than the locale's own currency
372    /// is shown as the code: this data has no symbols for other currencies,
373    /// and the locale's symbol would state the wrong one - `code: "EUR"`
374    /// used to print `$1,234.56` under `en`. A marker that meets the digits
375    /// with a letter (`EUR`, `CHF`) is set off by a no-break space, as CLDR's
376    /// currency spacing and ICU's `EUR 1,234.56` do.
377    fn push_currency(
378        &self,
379        out: &mut String,
380        number: &str,
381        code: Option<&'static str>,
382        symbol: Option<&'static str>,
383    ) {
384        let marker = match (symbol, code) {
385            (Some(symbol), _) => symbol,
386            (None, Some(code))
387                if !code.eq_ignore_ascii_case(self.symbols.default_currency_code) =>
388            {
389                code
390            }
391            (None, _) => self.symbols.default_currency_symbol,
392        };
393        match self.symbols.currency_placement {
394            CurrencyPlacement::Prefix => {
395                out.push_str(marker);
396                if marker.ends_with(char::is_alphabetic) {
397                    out.push('\u{a0}');
398                }
399                out.push_str(number);
400            }
401            CurrencyPlacement::PrefixWithSpace => {
402                out.push_str(marker);
403                out.push(' ');
404                out.push_str(number);
405            }
406            CurrencyPlacement::Suffix => {
407                out.push_str(number);
408                if marker.starts_with(char::is_alphabetic) {
409                    out.push('\u{a0}');
410                }
411                out.push_str(marker);
412            }
413            CurrencyPlacement::SuffixWithSpace => {
414                out.push_str(number);
415                out.push(' ');
416                out.push_str(marker);
417            }
418        }
419    }
420}
421
422/// Helper to insert group separators into an integer string.
423fn group_digits(digits: &str, group_sep: &str, group_size: usize) -> String {
424    if group_size == 0 || digits.len() <= group_size {
425        return digits.to_string();
426    }
427
428    let mut result =
429        String::with_capacity(digits.len() + (digits.len() / group_size) * group_sep.len());
430    let rem = digits.len() % group_size;
431
432    if rem > 0 {
433        result.push_str(&digits[..rem]);
434        if rem < digits.len() {
435            result.push_str(group_sep);
436        }
437    }
438
439    for (i, chunk) in digits.as_bytes()[rem..].chunks(group_size).enumerate() {
440        if i > 0 {
441            result.push_str(group_sep);
442        }
443        result.push_str(std::str::from_utf8(chunk).unwrap_or(""));
444    }
445
446    result
447}
448
449/// Round a float's *magnitude* into integer digits and fraction digits.
450///
451/// Rounding works on the shortest decimal that round-trips to `val`, which is
452/// what `Display` prints and what ICU rounds. It used to scale by
453/// `10^max_frac` in `f64` and cast to `u128`. That saturated from about 3.4e38,
454/// so `1e36` printed `u128::MAX` under the default three fraction digits and 40
455/// fraction digits turned `0.5` into `1`. It also moved values that were not
456/// ties: `(x + 0.5).floor()` took `0.49999999999999994` to 1 and `2^52 + 1` to
457/// `2^52 + 2`, and a `1e-9` tie tolerance sent `2.5000000001` to 2 under
458/// `HalfEven`. And it rounded the binary value rather than the decimal one the
459/// caller wrote: `Ceil` gave `1.1` as `1.11` and `Truncate` gave `0.29` as
460/// `0.28`.
461///
462/// `shift` moves the decimal point right before rounding, which is how percent
463/// scales by 100 exactly. A `min_frac` above `max_frac` wins, as it does in
464/// [`NumberFormatter::format_int`].
465///
466/// `val` is always non-negative: [`NumberFormatter::format_float`] splits the
467/// sign off before calling and re-attaches it afterwards. That split is only
468/// sound for the rounding modes that commute with `abs`. `HalfUp` (half away
469/// from zero), `HalfEven` and `Truncate` (toward zero) are all defined in terms
470/// of the magnitude already, so they survive it. `Floor` and `Ceil` are not:
471/// they are defined against the number line, so below zero `Floor` rounds the
472/// magnitude *up* and `Ceil` rounds it *down*. Rounding the bare magnitude
473/// under those names gave `-2.9` as `-2` under `Floor` and `-2.1` as `-3` under
474/// `Ceil` - each the opposite of what its own doc comment promises. Reflect
475/// them here, which is the last point where the sign is still known.
476fn round_float_parts(
477    val: f64,
478    shift: usize,
479    max_frac: usize,
480    min_frac: usize,
481    mode: RoundingMode,
482    is_negative: bool,
483) -> (String, String) {
484    let mode = if is_negative {
485        match mode {
486            // Toward -inf is away from zero; toward +inf is toward zero.
487            RoundingMode::Floor => RoundingMode::Ceil,
488            RoundingMode::Ceil => RoundingMode::Truncate,
489            symmetric => symmetric,
490        }
491    } else {
492        mode
493    };
494
495    // ASCII digits with the decimal point removed; `point` digits are integer.
496    // `Display` never uses an exponent, so the integer part is never empty.
497    let shortest = val.to_string();
498    let (int_digits, frac_digits) = shortest.split_once('.').unwrap_or((&shortest, ""));
499    let mut digits: Vec<u8> = int_digits.bytes().chain(frac_digits.bytes()).collect();
500    let mut point = int_digits.len() + shift;
501    if digits.len() < point {
502        digits.resize(point, b'0');
503    }
504
505    let keep = point.saturating_add(max_frac.max(min_frac));
506    let dropped = if digits.len() > keep {
507        digits.split_off(keep)
508    } else {
509        Vec::new()
510    };
511    let round_up = match mode {
512        RoundingMode::Truncate | RoundingMode::Floor => false,
513        RoundingMode::Ceil => dropped.iter().any(|&d| d != b'0'),
514        RoundingMode::HalfUp => dropped.first().is_some_and(|&d| d >= b'5'),
515        RoundingMode::HalfEven => match dropped.split_first() {
516            // An exact tie goes to the even neighbour.
517            Some((&b'5', rest)) if rest.iter().all(|&d| d == b'0') => {
518                digits.last().is_some_and(|&d| (d - b'0') % 2 == 1)
519            }
520            Some((&first, _)) => first >= b'5',
521            None => false,
522        },
523    };
524    if round_up {
525        // Trailing 9s carry: they become 0s and the digit before them takes 1.
526        if let Some(at) = digits.iter().rposition(|&d| d != b'9') {
527            digits[at] += 1;
528            digits[at + 1..].fill(b'0');
529        } else {
530            digits.fill(b'0');
531            digits.insert(0, b'1');
532            point += 1;
533        }
534    }
535
536    let frac_digits = digits.split_off(point);
537    let leading_zeros = digits
538        .iter()
539        .take_while(|&&d| d == b'0')
540        .count()
541        .min(digits.len() - 1);
542    let int_str = digits[leading_zeros..]
543        .iter()
544        .map(|&d| char::from(d))
545        .collect();
546
547    let mut frac_str: String = frac_digits.iter().map(|&d| char::from(d)).collect();
548    // Strip trailing zeros down to min_frac, then pad back up to it.
549    while frac_str.len() > min_frac && frac_str.ends_with('0') {
550        frac_str.pop();
551    }
552    frac_str.extend(std::iter::repeat_n(
553        '0',
554        min_frac.saturating_sub(frac_str.len()),
555    ));
556
557    (int_str, frac_str)
558}
559
560/// Convert ASCII digits in a string to Eastern Arabic numerals.
561fn convert_to_arab_digits(s: &str) -> String {
562    s.chars()
563        .map(|c| match c {
564            '0' => '٠',
565            '1' => '١',
566            '2' => '٢',
567            '3' => '٣',
568            '4' => '٤',
569            '5' => '٥',
570            '6' => '٦',
571            '7' => '٧',
572            '8' => '٨',
573            '9' => '٩',
574            _ => c,
575        })
576        .collect()
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582
583    #[test]
584    fn test_format_int_all_locales() {
585        let val = 1_234_567;
586        let en = NumberFormatter::for_locale("en").unwrap().format_int(val);
587        assert_eq!(en, "1,234,567");
588
589        let de = NumberFormatter::for_locale("de").unwrap().format_int(val);
590        assert_eq!(de, "1.234.567");
591
592        let fr = NumberFormatter::for_locale("fr").unwrap().format_int(val);
593        assert_eq!(fr, "1\u{202f}234\u{202f}567");
594
595        let es = NumberFormatter::for_locale("es").unwrap().format_int(val);
596        assert_eq!(es, "1.234.567");
597
598        let ru = NumberFormatter::for_locale("ru").unwrap().format_int(val);
599        assert_eq!(ru, "1\u{00a0}234\u{00a0}567");
600
601        let ar = NumberFormatter::for_locale("ar").unwrap().format_int(val);
602        assert_eq!(ar, "1,234,567");
603
604        let ja = NumberFormatter::for_locale("ja").unwrap().format_int(val);
605        assert_eq!(ja, "1,234,567");
606    }
607
608    #[test]
609    fn test_format_negative_int() {
610        let fmt = NumberFormatter::for_locale("en").unwrap();
611        assert_eq!(fmt.format_int(-42), "-42");
612        assert_eq!(fmt.format_int(-1000), "-1,000");
613    }
614
615    #[test]
616    fn test_format_float_decimal_separators() {
617        let val = 1234.56;
618        let cfg = NumberFormat::new().fraction_digits(2, 2);
619
620        let en = NumberFormatter::with_config("en", cfg)
621            .unwrap()
622            .format_float(val)
623            .unwrap();
624        assert_eq!(en, "1,234.56");
625
626        let de = NumberFormatter::with_config("de", cfg)
627            .unwrap()
628            .format_float(val)
629            .unwrap();
630        assert_eq!(de, "1.234,56");
631
632        let fr = NumberFormatter::with_config("fr", cfg)
633            .unwrap()
634            .format_float(val)
635            .unwrap();
636        assert_eq!(fr, "1\u{202f}234,56");
637
638        let es = NumberFormatter::with_config("es", cfg)
639            .unwrap()
640            .format_float(val)
641            .unwrap();
642        assert_eq!(es, "1.234,56");
643
644        let ru = NumberFormatter::with_config("ru", cfg)
645            .unwrap()
646            .format_float(val)
647            .unwrap();
648        assert_eq!(ru, "1\u{00a0}234,56");
649
650        let ar = NumberFormatter::with_config("ar", cfg)
651            .unwrap()
652            .format_float(val)
653            .unwrap();
654        assert_eq!(ar, "1,234.56");
655
656        let ja = NumberFormatter::with_config("ja", cfg)
657            .unwrap()
658            .format_float(val)
659            .unwrap();
660        assert_eq!(ja, "1,234.56");
661    }
662
663    #[test]
664    fn test_rounding_modes() {
665        let half_up_cfg = NumberFormat::new()
666            .fraction_digits(0, 0)
667            .rounding_mode(RoundingMode::HalfUp);
668        let half_even_cfg = NumberFormat::new()
669            .fraction_digits(0, 0)
670            .rounding_mode(RoundingMode::HalfEven);
671        let trunc_cfg = NumberFormat::new()
672            .fraction_digits(0, 0)
673            .rounding_mode(RoundingMode::Truncate);
674        let ceil_cfg = NumberFormat::new()
675            .fraction_digits(0, 0)
676            .rounding_mode(RoundingMode::Ceil);
677        let floor_cfg = NumberFormat::new()
678            .fraction_digits(0, 0)
679            .rounding_mode(RoundingMode::Floor);
680
681        let fmt_hu = NumberFormatter::with_config("en", half_up_cfg).unwrap();
682        let fmt_he = NumberFormatter::with_config("en", half_even_cfg).unwrap();
683        let fmt_tr = NumberFormatter::with_config("en", trunc_cfg).unwrap();
684        let fmt_ce = NumberFormatter::with_config("en", ceil_cfg).unwrap();
685        let fmt_fl = NumberFormatter::with_config("en", floor_cfg).unwrap();
686
687        // HalfUp: 2.5 -> 3, 3.5 -> 4
688        assert_eq!(fmt_hu.format_float(2.5).unwrap(), "3");
689        assert_eq!(fmt_hu.format_float(3.5).unwrap(), "4");
690
691        // HalfEven: 2.5 -> 2, 3.5 -> 4
692        assert_eq!(fmt_he.format_float(2.5).unwrap(), "2");
693        assert_eq!(fmt_he.format_float(3.5).unwrap(), "4");
694
695        // Truncate / Floor / Ceil
696        assert_eq!(fmt_tr.format_float(2.9).unwrap(), "2");
697        assert_eq!(fmt_fl.format_float(2.9).unwrap(), "2");
698        assert_eq!(fmt_ce.format_float(2.1).unwrap(), "3");
699    }
700
701    #[test]
702    fn floor_and_ceil_follow_the_number_line_below_zero() {
703        // `test_rounding_modes` above only ever feeds positive values, where
704        // every mode agrees with its magnitude-only form. These are the cases
705        // that separate them.
706        let with = |mode| {
707            NumberFormatter::with_config(
708                "en",
709                NumberFormat::new()
710                    .fraction_digits(0, 0)
711                    .rounding_mode(mode),
712            )
713            .unwrap()
714        };
715        let floor = with(RoundingMode::Floor);
716        let ceil = with(RoundingMode::Ceil);
717        let trunc = with(RoundingMode::Truncate);
718
719        // Floor is toward -inf: it moves *away* from zero on a negative value.
720        assert_eq!(floor.format_float(-2.1).unwrap(), "-3");
721        assert_eq!(floor.format_float(-2.9).unwrap(), "-3");
722        // Ceil is toward +inf: it moves *toward* zero on a negative value.
723        assert_eq!(ceil.format_float(-2.1).unwrap(), "-2");
724        assert_eq!(ceil.format_float(-2.9).unwrap(), "-2");
725        // Truncate is toward zero from both sides - what Floor used to do.
726        assert_eq!(trunc.format_float(-2.9).unwrap(), "-2");
727        assert_eq!(trunc.format_float(2.9).unwrap(), "2");
728        // Above zero the three are unchanged.
729        assert_eq!(floor.format_float(2.9).unwrap(), "2");
730        assert_eq!(ceil.format_float(2.1).unwrap(), "3");
731    }
732
733    #[test]
734    fn floor_and_ceil_reflect_at_fractional_precision_too() {
735        let with = |mode| {
736            NumberFormatter::with_config(
737                "en",
738                NumberFormat::new()
739                    .fraction_digits(2, 2)
740                    .rounding_mode(mode),
741            )
742            .unwrap()
743        };
744        assert_eq!(
745            with(RoundingMode::Floor).format_float(-1.234).unwrap(),
746            "-1.24"
747        );
748        assert_eq!(
749            with(RoundingMode::Ceil).format_float(-1.236).unwrap(),
750            "-1.23"
751        );
752        assert_eq!(
753            with(RoundingMode::Floor).format_float(1.236).unwrap(),
754            "1.23"
755        );
756        assert_eq!(
757            with(RoundingMode::Ceil).format_float(1.234).unwrap(),
758            "1.24"
759        );
760    }
761
762    fn format_with(min: usize, max: usize, mode: RoundingMode, value: f64) -> String {
763        NumberFormatter::with_config(
764            "en",
765            NumberFormat::new()
766                .fraction_digits(min, max)
767                .rounding_mode(mode),
768        )
769        .unwrap()
770        .format_float(value)
771        .unwrap()
772    }
773
774    // Expected strings are what ICU prints (Node's `Intl.NumberFormat`).
775
776    #[test]
777    fn large_values_and_long_fractions_keep_their_digits() {
778        // Scaling by 10^max_frac into a u128 saturated: both of these printed
779        // u128::MAX's digits, and forty fraction digits turned 0.5 into 1.
780        let default = NumberFormatter::for_locale("en").unwrap();
781        assert_eq!(
782            default.format_float(1e36).unwrap(),
783            "1,000,000,000,000,000,000,000,000,000,000,000,000"
784        );
785        assert!(
786            default
787                .format_float(f64::MAX)
788                .unwrap()
789                .starts_with("179,769,313,486,231,570,000,")
790        );
791        assert_eq!(format_with(0, 40, RoundingMode::HalfUp, 0.5), "0.5");
792    }
793
794    #[test]
795    fn rounding_reads_the_decimal_the_caller_wrote() {
796        // Each of these came out one unit off when rounded in binary.
797        assert_eq!(format_with(2, 2, RoundingMode::Ceil, 1.1), "1.10");
798        assert_eq!(format_with(2, 2, RoundingMode::Truncate, 0.29), "0.29");
799        assert_eq!(format_with(2, 2, RoundingMode::HalfUp, 1.005), "1.01");
800        // `(x + 0.5).floor()` rounds these up although neither is a tie.
801        assert_eq!(
802            format_with(0, 0, RoundingMode::HalfUp, 0.499_999_999_999_999_94),
803            "0"
804        );
805        assert_eq!(
806            format_with(0, 0, RoundingMode::HalfUp, 4_503_599_627_370_497.0),
807            "4,503,599,627,370,497"
808        );
809        // Only an exact tie goes to the even neighbour.
810        assert_eq!(
811            format_with(0, 0, RoundingMode::HalfEven, 2.500_000_000_1),
812            "3"
813        );
814        assert_eq!(format_with(0, 0, RoundingMode::HalfEven, 2.5), "2");
815        assert_eq!(format_with(1, 1, RoundingMode::HalfEven, 0.25), "0.2");
816    }
817
818    #[test]
819    fn percent_moves_the_decimal_point_instead_of_multiplying() {
820        let fmt = |mode| {
821            NumberFormatter::with_config(
822                "en",
823                NumberFormat::new()
824                    .style(NumberStyle::Percent)
825                    .rounding_mode(mode),
826            )
827            .unwrap()
828        };
829        // `0.29 * 100.0` is 28.999999999999996, which truncated to "28.999%".
830        assert_eq!(
831            fmt(RoundingMode::Truncate).format_float(0.29).unwrap(),
832            "29%"
833        );
834        // `1e307 * 100.0` overflowed to infinity.
835        assert!(
836            fmt(RoundingMode::HalfUp)
837                .format_float(1e307)
838                .unwrap()
839                .starts_with("1,000,000,")
840        );
841    }
842
843    #[test]
844    fn a_minimum_above_the_maximum_fraction_digits_wins_for_floats_too() {
845        let fmt =
846            NumberFormatter::with_config("en", NumberFormat::new().fraction_digits(3, 1)).unwrap();
847        assert_eq!(fmt.format_int(1), "1.000");
848        assert_eq!(fmt.format_float(1.0).unwrap(), "1.000");
849        assert_eq!(fmt.format_float(1.25).unwrap(), "1.250");
850    }
851
852    #[test]
853    fn percent_style_scales_ints_and_floats_alike() {
854        let fmt =
855            NumberFormatter::with_config("en", NumberFormat::new().style(NumberStyle::Percent))
856                .unwrap();
857
858        // `NumberStyle::Percent` promises "multiplied by 100"; both entry
859        // points have to keep that promise or one value renders two ways.
860        assert_eq!(fmt.format_int(12), "1,200%");
861        assert_eq!(fmt.format_float(12.0).unwrap(), "1,200%");
862        assert_eq!(fmt.format_int(-1), "-100%");
863        assert_eq!(fmt.format_int(0), "0%");
864
865        // `i128::MAX * 100` overflows `u128`, and `format_int` has no error
866        // channel, so the magnitude saturates instead of wrapping to a small
867        // number.
868        assert_eq!(
869            fmt.format_int(i128::MAX),
870            format!("{}%", group_digits(&u128::MAX.to_string(), ",", 3))
871        );
872    }
873
874    #[test]
875    fn test_currency_formatting() {
876        let cfg = NumberFormat::new()
877            .style(NumberStyle::Currency {
878                code: None,
879                symbol: None,
880            })
881            .fraction_digits(2, 2);
882
883        let en = NumberFormatter::with_config("en", cfg)
884            .unwrap()
885            .format_float(1234.56)
886            .unwrap();
887        assert_eq!(en, "$1,234.56");
888
889        let de = NumberFormatter::with_config("de", cfg)
890            .unwrap()
891            .format_float(1234.56)
892            .unwrap();
893        assert_eq!(de, "1.234,56 €");
894
895        let ru = NumberFormatter::with_config("ru", cfg)
896            .unwrap()
897            .format_float(1234.56)
898            .unwrap();
899        assert_eq!(ru, "1\u{00a0}234,56 ₽");
900
901        let ja = NumberFormatter::with_config("ja", cfg)
902            .unwrap()
903            .format_float(1234.56)
904            .unwrap();
905        assert_eq!(ja, "¥1,234.56");
906
907        let ar = NumberFormatter::with_config("ar", cfg)
908            .unwrap()
909            .format_float(1234.56)
910            .unwrap();
911        assert_eq!(ar, "1,234.56 ر.س");
912    }
913
914    #[test]
915    fn currency_code_names_the_currency_shown() {
916        let currency = |locale, code, symbol| {
917            NumberFormatter::with_config(
918                locale,
919                NumberFormat::new()
920                    .style(NumberStyle::Currency { code, symbol })
921                    .fraction_digits(2, 2),
922            )
923            .unwrap()
924        };
925        // The code was ignored, so euros came out as dollars under `en`.
926        // Expected strings are ICU's `currencyDisplay: "code"` output, except
927        // that this crate spaces a trailing marker with a plain space.
928        assert_eq!(
929            currency("en", Some("EUR"), None)
930                .format_float(-1234.56)
931                .unwrap(),
932            "-EUR\u{a0}1,234.56"
933        );
934        assert_eq!(
935            currency("de", Some("USD"), None)
936                .format_float(-1234.56)
937                .unwrap(),
938            "-1.234,56 USD"
939        );
940        assert_eq!(
941            currency("ja", Some("USD"), None).format_int(-5),
942            "-USD\u{a0}5.00"
943        );
944        // The locale's own currency keeps its symbol.
945        assert_eq!(
946            currency("en", Some("usd"), None)
947                .format_float(1234.56)
948                .unwrap(),
949            "$1,234.56"
950        );
951        // A symbol wins over the code; one ending in a letter is spaced.
952        assert_eq!(
953            currency("en", Some("EUR"), Some("€"))
954                .format_float(1234.56)
955                .unwrap(),
956            "€1,234.56"
957        );
958        assert_eq!(
959            currency("en", None, Some("CHF"))
960                .format_float(1234.56)
961                .unwrap(),
962            "CHF\u{a0}1,234.56"
963        );
964    }
965
966    #[test]
967    fn test_percent_formatting() {
968        let cfg = NumberFormat::new()
969            .style(NumberStyle::Percent)
970            .fraction_digits(1, 1);
971
972        let en = NumberFormatter::with_config("en", cfg)
973            .unwrap()
974            .format_float(0.125)
975            .unwrap();
976        assert_eq!(en, "12.5%");
977
978        let de = NumberFormatter::with_config("de", cfg)
979            .unwrap()
980            .format_float(0.125)
981            .unwrap();
982        assert_eq!(de, "12,5 %");
983    }
984
985    #[test]
986    fn test_eastern_arabic_digits() {
987        let cfg = NumberFormat::new()
988            .numbering_system(NumberingSystem::Arab)
989            .fraction_digits(0, 0);
990        let fmt = NumberFormatter::with_config("ar", cfg).unwrap();
991        assert_eq!(fmt.format_int(12345), "١٢,٣٤٥");
992    }
993
994    #[test]
995    fn test_non_finite_float_handling() {
996        let fmt_strict = NumberFormatter::for_locale("en").unwrap();
997        assert!(matches!(
998            fmt_strict.format_float(f64::NAN),
999            Err(FormattingError::NonFinite(_))
1000        ));
1001        assert!(matches!(
1002            fmt_strict.format_float(f64::INFINITY),
1003            Err(FormattingError::NonFinite(_))
1004        ));
1005
1006        let cfg = NumberFormat::new().allow_non_finite(true);
1007        let fmt_permissive = NumberFormatter::with_config("en", cfg).unwrap();
1008        assert_eq!(fmt_permissive.format_float(f64::NAN).unwrap(), "NaN");
1009        assert_eq!(fmt_permissive.format_float(f64::INFINITY).unwrap(), "∞");
1010        assert_eq!(
1011            fmt_permissive.format_float(f64::NEG_INFINITY).unwrap(),
1012            "-∞"
1013        );
1014    }
1015
1016    #[test]
1017    fn test_unsupported_locale() {
1018        let res = NumberFormatter::for_locale("xx-unsupported");
1019        assert!(matches!(res, Err(FormattingError::UnsupportedLocale(_))));
1020    }
1021}