1#![forbid(unsafe_code)]
2
3use super::data::{
6 CurrencyPlacement, LocaleData, NumberSymbols, PercentPlacement, lookup_locale_data,
7};
8use super::error::FormattingError;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12pub enum RoundingMode {
13 #[default]
15 HalfUp,
16 HalfEven,
18 Truncate,
20 Floor,
22 Ceil,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub enum NumberStyle {
29 #[default]
31 Decimal,
32 Percent,
34 Currency {
36 code: Option<&'static str>,
40 symbol: Option<&'static str>,
42 },
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub enum NumberingSystem {
48 #[default]
50 Latn,
51 Arab,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct NumberFormat {
58 pub min_integer_digits: usize,
60 pub min_fraction_digits: usize,
62 pub max_fraction_digits: usize,
64 pub use_grouping: bool,
66 pub rounding_mode: RoundingMode,
68 pub style: NumberStyle,
70 pub numbering_system: NumberingSystem,
72 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 #[must_use]
95 pub fn new() -> Self {
96 Self::default()
97 }
98
99 #[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 #[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 #[must_use]
116 pub const fn use_grouping(mut self, grouping: bool) -> Self {
117 self.use_grouping = grouping;
118 self
119 }
120
121 #[must_use]
123 pub const fn rounding_mode(mut self, mode: RoundingMode) -> Self {
124 self.rounding_mode = mode;
125 self
126 }
127
128 #[must_use]
130 pub const fn style(mut self, style: NumberStyle) -> Self {
131 self.style = style;
132 self
133 }
134
135 #[must_use]
137 pub const fn numbering_system(mut self, system: NumberingSystem) -> Self {
138 self.numbering_system = system;
139 self
140 }
141
142 #[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#[derive(Debug, Clone)]
152pub struct NumberFormatter {
153 locale_tag: String,
154 symbols: NumberSymbols,
155 config: NumberFormat,
156}
157
158impl NumberFormatter {
159 pub fn for_locale(locale: &str) -> Result<Self, FormattingError> {
164 Self::with_config(locale, NumberFormat::default())
165 }
166
167 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 #[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 #[must_use]
189 pub fn locale(&self) -> &str {
190 &self.locale_tag
191 }
192
193 #[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 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 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 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 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 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
422fn 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
449fn 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 RoundingMode::Floor => RoundingMode::Ceil,
488 RoundingMode::Ceil => RoundingMode::Truncate,
489 symmetric => symmetric,
490 }
491 } else {
492 mode
493 };
494
495 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 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 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 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
560fn 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 assert_eq!(fmt_hu.format_float(2.5).unwrap(), "3");
689 assert_eq!(fmt_hu.format_float(3.5).unwrap(), "4");
690
691 assert_eq!(fmt_he.format_float(2.5).unwrap(), "2");
693 assert_eq!(fmt_he.format_float(3.5).unwrap(), "4");
694
695 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 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 assert_eq!(floor.format_float(-2.1).unwrap(), "-3");
721 assert_eq!(floor.format_float(-2.9).unwrap(), "-3");
722 assert_eq!(ceil.format_float(-2.1).unwrap(), "-2");
724 assert_eq!(ceil.format_float(-2.9).unwrap(), "-2");
725 assert_eq!(trunc.format_float(-2.9).unwrap(), "-2");
727 assert_eq!(trunc.format_float(2.9).unwrap(), "2");
728 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 #[test]
777 fn large_values_and_long_fractions_keep_their_digits() {
778 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 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 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 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 assert_eq!(
831 fmt(RoundingMode::Truncate).format_float(0.29).unwrap(),
832 "29%"
833 );
834 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 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 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 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 assert_eq!(
946 currency("en", Some("usd"), None)
947 .format_float(1234.56)
948 .unwrap(),
949 "$1,234.56"
950 );
951 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}