waft_winui/controls/number_box/
formatter.rs1use std::any::Any;
6
7pub trait NumberFormatter {
12 fn format_double(&self, value: f64) -> String;
14
15 fn parse_double(&self, text: &str) -> Option<f64>;
17}
18
19pub trait ComparableNumberFormatter: NumberFormatter {
22 fn as_any(&self) -> &dyn Any;
24
25 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub struct DecimalFormatter {
46 pub integer_digits: usize,
48
49 pub fraction_digits: usize,
51}
52
53impl Default for DecimalFormatter {
54 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 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
117const DISPLAY_SIGNIFICANT_DIGITS: usize = 10;
119
120pub(super) fn round_for_display(value: f64) -> f64 {
124 round_to_significant_digits(value, DISPLAY_SIGNIFICANT_DIGITS)
125}
126
127fn round_to_significant_digits(value: f64, digits: usize) -> f64 {
129 if value == 0.0 || !value.is_finite() {
130 return value;
131 }
132 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 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}