Skip to main content

ferrochart_core/
format.rs

1//! Number formats of axis and value labels: fixed decimals, automatic
2//! precision with subscript zeros, percentages and K/M/B.
3//!
4
5use core::fmt::Write;
6
7/// How numbers are written on axes and labels (price axis, `Plot` axes,
8/// value labels).
9///
10/// ```
11/// use ferrochart_core::format::NumberFormat;
12///
13/// let mut s = String::new();
14/// NumberFormat::Auto(8).write(&mut s, 0.000_012_34);
15/// assert_eq!(s, "0.0₄1234");
16/// s.clear();
17/// NumberFormat::Compact.write(&mut s, 1_250_000.0);
18/// assert_eq!(s, "1.25M");
19/// ```
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum NumberFormat {
22    /// Fixed decimals (a price series with a set precision).
23    Fixed(u8),
24    /// Automatic precision with these decimals: subscript zeros below 1.
25    Auto(u8),
26    /// Fixed decimals with a `%` suffix (percentage scales).
27    Percent(u8),
28    /// K/M/B suffixes (a volume-only pane).
29    Compact,
30}
31
32impl NumberFormat {
33    /// Writes the label of `v`.
34    pub fn write(self, out: &mut impl core::fmt::Write, v: f64) {
35        use crate::price_scale::{write_compact, write_price};
36        match self {
37            Self::Fixed(p) => write_price(out, v, p),
38            Self::Auto(p) => write_price_auto(out, v, p),
39            Self::Percent(p) => {
40                write_price(out, v, p);
41                let _ = out.write_char('%');
42            }
43            Self::Compact => write_compact(out, v),
44        }
45    }
46
47    /// The format for the axis ticks `ticks`: fixed decimals are widened
48    /// (up to 30) until every tick is written exactly, so neighbouring ticks
49    /// never read the same when the tick step is finer than the precision.
50    #[must_use]
51    pub fn for_ticks(self, ticks: &[f64]) -> Self {
52        let widen = |p: u8| {
53            ticks.iter().fold(p, |d, &t| {
54                let mut d = d;
55                while d < 30 {
56                    let x = t * 10f64.powi(i32::from(d));
57                    if (x - x.round()).abs() <= 1e-12 * x.abs().max(1.0) {
58                        break;
59                    }
60                    d += 1;
61                }
62                d
63            })
64        };
65        match self {
66            Self::Fixed(p) => Self::Fixed(widen(p)),
67            Self::Auto(p) => Self::Auto(widen(p)),
68            Self::Percent(p) => Self::Percent(widen(p)),
69            Self::Compact => Self::Compact,
70        }
71    }
72}
73
74/// Decimals of automatic precision for prices of magnitude `magnitude`: at
75/// least 2 decimals and 4 significant digits, at most 30; 2 for zero or
76/// non-finite magnitudes.
77pub fn auto_decimals(magnitude: f64) -> u8 {
78    let m = magnitude.abs();
79    if !(m.is_finite() && m > 0.0) {
80        return 2;
81    }
82    // floor(log10 m), corrected where log10 is off by an ulp at a power of 10.
83    let mut e = m.log10().floor();
84    if 10f64.powf(e) > m {
85        e -= 1.0;
86    } else if 10f64.powf(e + 1.0) <= m {
87        e += 1.0;
88    }
89    (3.0 - e).clamp(2.0, 30.0) as u8
90}
91
92/// Writes `price` with `decimals` decimals in the automatic style: below 1,
93/// four or more zeros after the point become `0.0` and a subscript count
94/// (`0.0₄1234`); with four or more decimals, a price that rounds to zero
95/// is `0`.
96pub(crate) fn write_price_auto(out: &mut impl Write, price: f64, decimals: u8) {
97    if price.is_nan() || price.abs() >= 1.0 {
98        crate::price_scale::write_price(out, price, decimals);
99        return;
100    }
101    let mut s = crate::text::StackStr::<64>::new();
102    crate::price_scale::write_price(&mut s, price, decimals);
103    let text = s.as_str();
104    let (sign, unsigned) = text.strip_prefix('-').map_or(("", text), |r| ("-", r));
105    let Some(fraction) = unsigned.strip_prefix("0.") else {
106        let _ = out.write_str(text); // rounded up to 1
107        return;
108    };
109    let digits = fraction.trim_start_matches('0');
110    let zeros = fraction.len() - digits.len();
111    if zeros < 4 {
112        let _ = out.write_str(text);
113    } else if digits.is_empty() {
114        let _ = out.write_char('0');
115    } else {
116        let _ = out.write_str(sign);
117        let _ = out.write_str("0.0");
118        let (tens, ones) = (zeros / 10, zeros % 10);
119        for d in [tens, ones].into_iter().skip(usize::from(tens == 0)) {
120            let _ = out.write_char(char::from_u32(0x2080 + d as u32).unwrap_or('0'));
121        }
122        let _ = out.write_str(digits);
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn tick_labels_widen_to_the_tick_step() {
132        let ticks: Vec<f64> = (0..5).map(|m| f64::from(m) * 0.0025 + 1.0).collect();
133        assert_eq!(
134            NumberFormat::Fixed(2).for_ticks(&ticks),
135            NumberFormat::Fixed(4)
136        );
137        assert_eq!(
138            NumberFormat::Percent(0).for_ticks(&[0.5, 1.0]),
139            NumberFormat::Percent(1)
140        );
141        // Coarser steps keep the precision; it is never narrowed.
142        assert_eq!(
143            NumberFormat::Fixed(2).for_ticks(&[100.0, 150.0]),
144            NumberFormat::Fixed(2)
145        );
146        assert_eq!(
147            NumberFormat::Fixed(0).for_ticks(&[1e6, 2e6]),
148            NumberFormat::Fixed(0)
149        );
150        assert_eq!(
151            NumberFormat::Fixed(2).for_ticks(&[1.0 / 3.0]),
152            NumberFormat::Fixed(12) // exact within 1e-12
153        );
154        assert_eq!(
155            NumberFormat::Auto(8).for_ticks(&[0.000_012_345, 0.000_012_35]),
156            NumberFormat::Auto(9)
157        );
158        assert_eq!(
159            NumberFormat::Compact.for_ticks(&[0.5]),
160            NumberFormat::Compact
161        );
162    }
163}