plotters_unstable/data/
float.rs

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
16fn float_to_string(n: f64, max_precision: usize) -> String {
17    let (sign, n) = if n < 0.0 { ("-", -n) } else { ("", n) };
18    let int_part = n.floor();
19
20    let dec_part =
21        ((n.abs() - int_part.abs()) * (10.0f64).powf(max_precision as f64)).round() as u64;
22
23    if dec_part == 0 || max_precision == 0 {
24        return format!("{}{:.0}", sign, int_part);
25    }
26
27    let mut leading = "".to_string();
28    let mut dec_result = format!("{}", dec_part);
29
30    for _ in 0..(max_precision - dec_result.len()) {
31        leading.push('0');
32    }
33
34    while let Some(c) = dec_result.pop() {
35        if c != '0' {
36            dec_result.push(c);
37            break;
38        }
39    }
40
41    format!("{}{:.0}.{}{}", sign, int_part, leading, dec_result)
42}
43
44/// The function that pretty prints the floating number
45/// Since rust doesn't have anything that can format a float with out appearance, so we just
46/// implemnet a float pretty printing function, which finds the shortest representation of a
47/// floating point number within the allowed error range.
48///
49/// - `n`: The float number to pretty-print
50/// - `allow_sn`: Should we use scientific notation when possible
51/// - **returns**: The pretty printed string
52pub fn pretty_print_float(n: f64, allow_sn: bool) -> String {
53    let (n, p) = find_minimal_repr(n, 1e-10);
54    let d_repr = float_to_string(n, p);
55    if !allow_sn {
56        d_repr
57    } else {
58        if n == 0.0 {
59            return "0".to_string();
60        }
61
62        let mut idx = n.abs().log10().floor();
63        let mut exp = (10.0f64).powf(idx);
64
65        if n.abs() / exp + 1e-5 >= 10.0 {
66            idx += 1.0;
67            exp *= 10.0;
68        }
69
70        if idx.abs() < 3.0 {
71            return d_repr;
72        }
73
74        let (sn, sp) = find_minimal_repr(n / exp, 1e-5);
75        let s_repr = format!("{}e{}", float_to_string(sn, sp), float_to_string(idx, 0));
76        if s_repr.len() + 1 < d_repr.len() {
77            s_repr
78        } else {
79            d_repr
80        }
81    }
82}
83
84#[cfg(test)]
85mod test {
86    use super::*;
87    #[test]
88    fn test_pretty_printing() {
89        assert_eq!(pretty_print_float(0.99999999999999999999, false), "1");
90        assert_eq!(pretty_print_float(0.9999, false), "0.9999");
91        assert_eq!(
92            pretty_print_float(-1e-5 - 0.00000000000000001, true),
93            "-1e-5"
94        );
95        assert_eq!(
96            pretty_print_float(-1e-5 - 0.00000000000000001, false),
97            "-0.00001"
98        );
99        assert_eq!(pretty_print_float(1e100, true), "1e100");
100        assert_eq!(pretty_print_float(1234567890f64, true), "1234567890");
101        assert_eq!(pretty_print_float(1000000001f64, true), "1e9");
102    }
103}