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