injective_math/fp_decimal/
display.rs

1use crate::{
2    fp_decimal::FPDecimal,
3    scale::{Scaled, DEC_SCALE_FACTOR},
4};
5use std::fmt;
6
7impl fmt::Display for FPDecimal {
8    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9        let sign = if self.sign == 0 { "-" } else { "" };
10        let integer = self.int().abs();
11        let fraction = (FPDecimal::_fraction(*self)).abs();
12
13        if fraction == FPDecimal::ZERO {
14            write!(f, "{}{}", sign, integer.num / FPDecimal::ONE.num)
15        } else {
16            let fraction_string = fraction.num.to_string(); //
17            let fraction_string = "0".repeat(FPDecimal::DIGITS - fraction_string.len()) + &fraction_string;
18            let integer_num = integer.num / FPDecimal::ONE.num;
19            f.write_str(sign)?;
20            f.write_str(&integer_num.to_string())?;
21            f.write_str(".")?;
22            f.write_str(fraction_string.trim_end_matches('0'))?;
23
24            Ok(())
25        }
26    }
27}
28
29pub trait ToProto {
30    fn to_proto_string(self) -> String;
31}
32
33impl ToProto for FPDecimal {
34    fn to_proto_string(self) -> String {
35        self.scaled(DEC_SCALE_FACTOR).to_string()
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use crate::FPDecimal;
42
43    #[test]
44    fn test_fmt_sub() {
45        let input: FPDecimal = FPDecimal::ONE + FPDecimal::from(3u128).div(100i128);
46        assert_eq!(&format!("{input}"), "1.03");
47    }
48
49    #[test]
50    fn test_fmt() {
51        assert_eq!(&format!("{}", FPDecimal::LN_1_5), "0.405465108108164382");
52    }
53
54    #[test]
55    fn test_fmt_neg() {
56        assert_eq!(&format!("{}", -FPDecimal::FIVE), "-5");
57    }
58}