1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// ---------------------------------------------------------------------------
// Copyright:   (c) 2021 ff. Michael Amrhein (michael@adrhinum.de)
// License:     This program is part of a larger application. For license
//              details please read the file LICENSE.TXT provided together
//              with the application.
// ---------------------------------------------------------------------------
// $Source: src/format.rs $
// $Revision: 2021-10-29T12:14:58+02:00 $

use std::{
    cmp::{min, Ordering},
    fmt,
};

use num::{integer::div_mod_floor, Integer};
use rust_fixed_point_decimal_core::ten_pow;

use crate::{
    prec_constraints::{PrecLimitCheck, True},
    rounding::div_rounded,
    Decimal, MAX_PREC,
};

impl<const P: u8> fmt::Debug for Decimal<P>
where
    PrecLimitCheck<{ P <= MAX_PREC }>: True,
{
    fn fmt(&self, form: &mut fmt::Formatter<'_>) -> fmt::Result {
        if P == 0 {
            write!(form, "Dec!({})", self.coeff)
        } else {
            let (int, frac) = div_mod_floor(self.coeff, ten_pow(P));
            write!(form, "Dec!({}.{:0width$})", int, frac, width = P as usize)
        }
    }
}

#[cfg(test)]
mod test_fmt_debug {
    use super::*;

    #[test]
    fn test_fmt() {
        let d = Decimal::<3>::new_raw(1234567890002);
        assert_eq!(format!("{:?}", d), "Dec!(1234567890.002)");
        let d = Decimal::<9>::new_raw(-1230000000000);
        assert_eq!(format!("{:?}", d), "Dec!(-1230.000000000)");
        let d = Decimal::<0>::new_raw(1234567890002);
        assert_eq!(format!("{:?}", d), "Dec!(1234567890002)");
    }
}

impl<const P: u8> fmt::Display for Decimal<P>
where
    PrecLimitCheck<{ P <= MAX_PREC }>: True,
{
    /// Formats the value using the given formatter.
    ///
    /// If the format specifies less fractional digits than `self.precision()`,
    /// the value gets rounded according to the default rounding mode.
    ///
    /// # Examples:
    ///
    /// ```rust
    /// # #![allow(incomplete_features)]
    /// # #![feature(generic_const_exprs)]
    /// # use std::fmt;
    /// # use rust_fixed_point_decimal::{Dec, Decimal};
    /// let d = Dec!(-1234.56);
    /// assert_eq!(format!("{}", d), "-1234.56");
    /// assert_eq!(format!("{:014.3}", d), "-000001234.560");
    /// assert_eq!(format!("{:10.1}", d), "   -1234.6");
    /// ```
    fn fmt(&self, form: &mut fmt::Formatter<'_>) -> fmt::Result {
        let tmp: String;
        let prec = match form.precision() {
            Some(prec) => min(prec, MAX_PREC as usize),
            None => P as usize,
        };
        if P == 0 {
            if prec > 0 {
                tmp =
                    format!("{}.{:0width$}", self.coeff.abs(), 0, width = prec);
            } else {
                tmp = self.coeff.abs().to_string();
            }
        } else {
            let (int, frac) = match prec.cmp(&(P as usize)) {
                Ordering::Equal => self.coeff.abs().div_mod_floor(&ten_pow(P)),
                Ordering::Less => {
                    // Important: first round, then take abs() !
                    let coeff =
                        div_rounded(self.coeff, ten_pow(P - prec as u8), None);
                    coeff.abs().div_mod_floor(&ten_pow(prec as u8))
                }
                Ordering::Greater => {
                    let (int, frac) =
                        self.coeff.abs().div_mod_floor(&ten_pow(P));
                    (int, frac * ten_pow(prec as u8 - P))
                }
            };
            if prec > 0 {
                tmp = format!("{}.{:0width$}", int, frac, width = prec);
            } else {
                tmp = int.to_string();
            }
        }
        form.pad_integral(!self.is_negative(), "", &tmp)
    }
}

#[cfg(test)]
mod test_fmt_display {
    use super::*;

    #[test]
    fn test_fmt_decimal_0() {
        let d = Decimal::<0>::new_raw(1234567890002);
        assert_eq!(d.to_string(), "1234567890002");
        assert_eq!(format!("{}", d), "1234567890002");
        assert_eq!(format!("{:<15}", d), "1234567890002  ");
        assert_eq!(format!("{:^15}", d), " 1234567890002 ");
        assert_eq!(format!("{:>15}", d), "  1234567890002");
        assert_eq!(format!("{:15}", d), "  1234567890002");
        assert_eq!(format!("{:015}", d), "001234567890002");
        assert_eq!(format!("{:010.2}", d), "1234567890002.00");
        let d = Decimal::<0>::new_raw(-12345);
        assert_eq!(d.to_string(), "-12345");
        assert_eq!(format!("{}", d), "-12345");
        assert_eq!(format!("{:10}", d), "    -12345");
        assert_eq!(format!("{:010}", d), "-000012345");
        assert_eq!(format!("{:012.3}", d), "-0012345.000");
    }

    #[test]
    fn test_fmt_decimal_without_rounding() {
        let d = Decimal::<4>::new_raw(1234567890002);
        assert_eq!(d.to_string(), "123456789.0002");
        assert_eq!(format!("{}", d), "123456789.0002");
        assert_eq!(format!("{:<15}", d), "123456789.0002 ");
        assert_eq!(format!("{:^17}", d), " 123456789.0002  ");
        assert_eq!(format!("{:>15}", d), " 123456789.0002");
        assert_eq!(format!("{:15}", d), " 123456789.0002");
        assert_eq!(format!("{:015}", d), "0123456789.0002");
        assert_eq!(format!("{:010.7}", d), "123456789.0002000");
        let d = Decimal::<2>::new_raw(-12345);
        assert_eq!(d.to_string(), "-123.45");
        assert_eq!(format!("{}", d), "-123.45");
        assert_eq!(format!("{:10}", d), "   -123.45");
        assert_eq!(format!("{:010}", d), "-000123.45");
        assert_eq!(format!("{:012.3}", d), "-0000123.450");
        let d = Decimal::<7>::new_raw(-12345);
        assert_eq!(d.to_string(), "-0.0012345");
        assert_eq!(format!("{}", d), "-0.0012345");
    }

    #[test]
    fn test_fmt_decimal_with_rounding() {
        let d = Decimal::<5>::new_raw(1234567890002);
        assert_eq!(format!("{:.4}", d), "12345678.9000");
        assert_eq!(format!("{:<15.2}", d), "12345678.90    ");
        assert_eq!(format!("{:.0}", d), "12345679");
        let d = Decimal::<7>::new_raw(-12347);
        assert_eq!(format!("{:.3}", d), "-0.001");
        assert_eq!(format!("{:10.5}", d), "  -0.00123");
        assert_eq!(format!("{:010.6}", d), "-00.001235");
    }
}