Skip to main content

waft_winui/controls/number_box/
formatter.rs

1//! The number formatting NumberBox leaves to `Windows.Globalization.NumberFormatting`: the
2//! interfaces of its `NumberFormatter` property, the `DecimalFormatter` it creates by default,
3//! and the `SignificantDigitsNumberRounder` it rounds a value with before formatting it.
4
5use std::any::Any;
6
7/// `NumberFormatter`: what NumberBox's `NumberFormatter` property holds, an object that is both
8/// an `INumberFormatter2` and an `INumberParser` (`NumberBox::ValidateNumberFormatter`).
9/// NumberBox formats its value with `format_double` and reads what is typed with
10/// `parse_double`.
11pub trait NumberFormatter {
12    /// `INumberFormatter2::FormatDouble`: the text shown for `value`.
13    fn format_double(&self, value: f64) -> String;
14
15    /// `INumberParser::ParseDouble`: the number `text` spells, or `None` when it spells none.
16    fn parse_double(&self, text: &str) -> Option<f64>;
17}
18
19/// A [`NumberFormatter`] NumberBox can tell from another: every `NumberFormatter` with
20/// `PartialEq` is one, so an equal formatter built again leaves the box's text alone.
21pub trait ComparableNumberFormatter: NumberFormatter {
22    /// The formatter as `Any`, to compare it with one of the same type.
23    fn as_any(&self) -> &dyn Any;
24
25    /// Whether `other` is a formatter of the same type and value.
26    fn same_as(&self, other: &dyn ComparableNumberFormatter) -> bool;
27}
28
29impl<F: NumberFormatter + PartialEq + 'static> ComparableNumberFormatter for F {
30    fn as_any(&self) -> &dyn Any {
31        self
32    }
33
34    fn same_as(&self, other: &dyn ComparableNumberFormatter) -> bool {
35        other.as_any().downcast_ref::<F>() == Some(self)
36    }
37}
38
39/// `DecimalFormatter` as `NumberBox::GetRegionalSettingsAwareDecimalFormatter` makes it, in the
40/// en-US conventions: a value in its shortest exact decimal form, with at least
41/// `integer_digits` digits before a `.` and `fraction_digits` after it, without grouping, and a
42/// `-` before a negative value but not before zero. It reads an optional `-`, digits and at
43/// most one `.`; grouping separators, exponents and other signs are not numbers to it.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct DecimalFormatter {
46    /// `IntegerDigits`: the fewest digits before the decimal point, padded with zeros.
47    pub integer_digits: usize,
48
49    /// `FractionDigits`: the fewest digits after the decimal point, padded with zeros.
50    pub fraction_digits: usize,
51}
52
53impl Default for DecimalFormatter {
54    /// NumberBox's: `IntegerDigits(1)` and `FractionDigits(0)`.
55    fn default() -> Self {
56        Self {
57            integer_digits: 1,
58            fraction_digits: 0,
59        }
60    }
61}
62
63impl NumberFormatter for DecimalFormatter {
64    fn format_double(&self, value: f64) -> String {
65        if value.is_nan() {
66            return "NaN".to_owned();
67        }
68        if value.is_infinite() {
69            return if value > 0.0 { "∞" } else { "-∞" }.to_owned();
70        }
71        // Rust's `Display` writes the shortest decimal that reads back as `value`, never with an
72        // exponent.
73        let digits = value.abs().to_string();
74        let (integer, fraction) = digits.split_once('.').unwrap_or((&digits, ""));
75        let integer = integer.trim_start_matches('0');
76        let mut text = String::new();
77        if value < 0.0 {
78            text.push('-');
79        }
80        let integer_digits = if integer.is_empty() && fraction.is_empty() {
81            self.integer_digits.max(1)
82        } else {
83            self.integer_digits
84        };
85        text.extend(std::iter::repeat_n(
86            '0',
87            integer_digits.saturating_sub(integer.len()),
88        ));
89        text.push_str(integer);
90        let padding = self.fraction_digits.saturating_sub(fraction.len());
91        if !fraction.is_empty() || padding > 0 {
92            text.push('.');
93            text.push_str(fraction);
94            text.extend(std::iter::repeat_n('0', padding));
95        }
96        text
97    }
98
99    fn parse_double(&self, text: &str) -> Option<f64> {
100        let unsigned = text.strip_prefix('-').unwrap_or(text);
101        let mut digits = 0;
102        let mut points = 0;
103        for character in unsigned.chars() {
104            match character {
105                '0'..='9' => digits += 1,
106                '.' => points += 1,
107                _ => return None,
108            }
109        }
110        if digits == 0 || points > 1 {
111            return None;
112        }
113        text.parse().ok()
114    }
115}
116
117/// `m_displayRounder.SignificantDigits(10)` in `NumberBox::OnApplyTemplate`.
118const DISPLAY_SIGNIFICANT_DIGITS: usize = 10;
119
120/// `m_displayRounder.RoundDouble`: NumberBox's `SignificantDigitsNumberRounder`, which keeps 10
121/// significant digits so that floating-point noise is not shown. A value that lies halfway
122/// rounds toward positive infinity, as `RoundHalfUp` does.
123pub(super) fn round_for_display(value: f64) -> f64 {
124    round_to_significant_digits(value, DISPLAY_SIGNIFICANT_DIGITS)
125}
126
127/// `value` with `digits` significant digits, halfway values rounding toward positive infinity.
128fn round_to_significant_digits(value: f64, digits: usize) -> f64 {
129    if value == 0.0 || !value.is_finite() {
130        return value;
131    }
132    // One digit more than kept, in Rust's correctly rounded formatting, shows whether `value`
133    // is the decimal halfway between two kept values.
134    let one_more = format!("{value:.digits$e}");
135    let halfway = one_more
136        .split_once('e')
137        .is_some_and(|(mantissa, _)| mantissa.ends_with('5'))
138        && one_more.parse::<f64>() == Ok(value);
139    // Formatting rounds halfway values to even; the next value up rounds them up instead.
140    let value = if halfway { value.next_up() } else { value };
141    let kept = digits - 1;
142    format!("{value:.kept$e}")
143        .parse()
144        .expect("Rust reads back the numbers it formats")
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn the_default_formatter_writes_the_shortest_decimal_without_grouping() {
153        let formatter = DecimalFormatter::default();
154        assert_eq!(formatter.format_double(0.0), "0");
155        assert_eq!(formatter.format_double(-0.0), "0");
156        assert_eq!(formatter.format_double(3.0), "3");
157        assert_eq!(formatter.format_double(-12.5), "-12.5");
158        assert_eq!(formatter.format_double(1234567.0), "1234567");
159        assert_eq!(formatter.format_double(0.25), "0.25");
160        assert_eq!(formatter.format_double(1e-7), "0.0000001");
161    }
162
163    #[test]
164    fn integer_and_fraction_digits_pad_with_zeros() {
165        let formatter = DecimalFormatter {
166            integer_digits: 3,
167            fraction_digits: 2,
168        };
169        assert_eq!(formatter.format_double(5.0), "005.00");
170        assert_eq!(formatter.format_double(-0.125), "-000.125");
171        let bare = DecimalFormatter {
172            integer_digits: 0,
173            fraction_digits: 0,
174        };
175        assert_eq!(bare.format_double(0.5), ".5");
176        assert_eq!(bare.format_double(0.0), "0");
177    }
178
179    #[test]
180    fn parsing_takes_a_minus_digits_and_one_point() {
181        let formatter = DecimalFormatter::default();
182        assert_eq!(formatter.parse_double("42"), Some(42.0));
183        assert_eq!(formatter.parse_double("-3.5"), Some(-3.5));
184        assert_eq!(formatter.parse_double(".5"), Some(0.5));
185        assert_eq!(formatter.parse_double("5."), Some(5.0));
186        for text in [
187            "", "-", ".", "1.2.3", "1,000", "1e3", "+1", " 1", "abc", "inf", "NaN",
188        ] {
189            assert_eq!(formatter.parse_double(text), None, "{text:?}");
190        }
191    }
192
193    #[test]
194    fn the_display_rounder_hides_floating_point_noise() {
195        assert_eq!(round_for_display(0.1 + 0.2), 0.3);
196        assert_eq!(round_for_display(1.0 / 3.0), 0.3333333333);
197        assert_eq!(round_for_display(12345678901234.0), 12345678900000.0);
198        assert_eq!(round_for_display(-2.0 / 3.0), -0.6666666667);
199        assert!(round_for_display(f64::NAN).is_nan());
200        assert_eq!(round_for_display(0.0), 0.0);
201    }
202
203    #[test]
204    fn a_halfway_value_rounds_toward_positive_infinity() {
205        assert_eq!(round_for_display(1234567890.5), 1234567891.0);
206        assert_eq!(round_for_display(-1234567890.5), -1234567890.0);
207        assert_eq!(round_for_display(1234567891.5), 1234567892.0);
208    }
209}