1// The code that is related to float number handling
2fn find_minimal_repr(n: f64, eps: f64) -> (f64, usize) {
3 if eps >= 1.0 {
4 return (n, 0);
5 }
6 if n - n.floor() < eps {
7 (n.floor(), 0)
8 } else if n.ceil() - n < eps {
9 (n.ceil(), 0)
10 } else {
11 let (rem, pre) = find_minimal_repr((n - n.floor()) * 10.0, eps * 10.0);
12 (n.floor() + rem / 10.0, pre + 1)
13 }
14}
15
16#[allow(clippy::never_loop)]
17fn float_to_string(n: f64, max_precision: usize, min_decimal: usize) -> String {
18 let (mut result, mut count) = loop {
19 let (sign, n) = if n < 0.0 { ("-", -n) } else { ("", n) };
20 let int_part = n.floor();
21
22 let dec_part =
23 ((n.abs() - int_part.abs()) * (10.0f64).powi(max_precision as i32)).round() as u64;
24
25 if dec_part == 0 || max_precision == 0 {
26 break (format!("{}{:.0}", sign, int_part), 0);
27 }
28
29 let mut leading = "".to_string();
30 let mut dec_result = format!("{}", dec_part);
31
32 for _ in 0..(max_precision - dec_result.len()) {
33 leading.push('0');
34 }
35
36 while let Some(c) = dec_result.pop() {
37 if c != '0' {
38 dec_result.push(c);
39 break;
40 }
41 }
42
43 break (
44 format!("{}{:.0}.{}{}", sign, int_part, leading, dec_result),
45 leading.len() + dec_result.len(),
46 );
47 };
48
49 if count == 0 && min_decimal > 0 {
50 result.push('.');
51 }
52
53 while count < min_decimal {
54 result.push('0');
55 count += 1;
56 }
57 result
58}
59
60/// Handles printing of floating point numbers
61pub struct FloatPrettyPrinter {
62 /// Whether scientific notation is allowed
63 pub allow_scientific: bool,
64 /// Minimum allowed number of decimal digits
65 pub min_decimal: i32,
66 /// Maximum allowed number of decimal digits
67 pub max_decimal: i32,
68}
69
70impl FloatPrettyPrinter {
71 /// Handles printing of floating point numbers
72 pub fn print(&self, n: f64) -> String {
73 let (tn, p) = find_minimal_repr(n, (10f64).powi(-self.max_decimal));
74 let d_repr = float_to_string(tn, p, self.min_decimal as usize);
75 if !self.allow_scientific {
76 d_repr
77 } else {
78 if n == 0.0 {
79 return "0".to_string();
80 }
81
82 let mut idx = n.abs().log10().floor();
83 let mut exp = (10.0f64).powf(idx);
84
85 if n.abs() / exp + 1e-5 >= 10.0 {
86 idx += 1.0;
87 exp *= 10.0;
88 }
89
90 if idx.abs() < 3.0 {
91 return d_repr;
92 }
93
94 let (sn, sp) = find_minimal_repr(n / exp, 1e-5);
95 let s_repr = format!(
96 "{}e{}",
97 float_to_string(sn, sp, self.min_decimal as usize),
98 float_to_string(idx, 0, 0)
99 );
100 if s_repr.len() + 1 < d_repr.len() || (tn == 0.0 && n != 0.0) {
101 s_repr
102 } else {
103 d_repr
104 }
105 }
106 }
107}
108
109/// The function that pretty prints the floating number
110/// Since rust doesn't have anything that can format a float with out appearance, so we just
111/// implement a float pretty printing function, which finds the shortest representation of a
112/// floating point number within the allowed error range.
113///
114/// - `n`: The float number to pretty-print
115/// - `allow_sn`: Should we use scientific notation when possible
116/// - **returns**: The pretty printed string
117pub fn pretty_print_float(n: f64, allow_sn: bool) -> String {
118 (FloatPrettyPrinter {
119 allow_scientific: allow_sn,
120 min_decimal: 0,
121 max_decimal: 10,
122 })
123 .print(n)
124}
125
126#[cfg(test)]
127mod test {
128 use super::*;
129 #[test]
130 fn test_pretty_printing() {
131 assert_eq!(pretty_print_float(0.99999999999999999999, false), "1");
132 assert_eq!(pretty_print_float(0.9999, false), "0.9999");
133 assert_eq!(
134 pretty_print_float(-1e-5 - 0.00000000000000001, true),
135 "-1e-5"
136 );
137 assert_eq!(
138 pretty_print_float(-1e-5 - 0.00000000000000001, false),
139 "-0.00001"
140 );
141 assert_eq!(pretty_print_float(1e100, true), "1e100");
142 assert_eq!(pretty_print_float(1234567890f64, true), "1234567890");
143 assert_eq!(pretty_print_float(1000000001f64, true), "1e9");
144 }
145}
146