Skip to main content

accounting/format_number/
mod.rs

1//! Define and implement FormatNumber trait. 
2//! 
3//! This trait be used for formatting numberic types to string with custom precision and separators.
4//! Implemented types include:
5//! * primitive type: i8, u8, i16, u16 i32, u32 i64, u64, i128, u128, isize, usize, f32, f64.
6//! * decimal type: `rust_decimal::Decimal`
7//!
8//! # Examples
9//! 
10//! ```
11//! # use accounting::FormatNumber;
12//! let x = 123456789.213123f64;
13//! assert_eq!(x.format_number(2, ",", "."), "123,456,789.21");
14//! 
15//! #[cfg(feature="decimal")]
16//! {
17//!     use rust_decimal::Decimal;
18//!     let x = Decimal::new(12345678921, 2);
19//!     assert_eq!( x.format_number(2, ",", "."), "123,456,789.21"); 
20//! }
21//! ```
22
23mod primitive;
24#[cfg(feature = "decimal")]
25mod decimal;
26
27/// Trait for formatting numbers with custom precision and separators. 
28pub trait FormatNumber {
29    fn format_number(&self, precision: usize, thousand: &str, decimal: &str) -> String;
30}
31
32
33#[cfg(test)]
34mod tests {
35	use super::*;
36	#[test]
37	fn format_number_int_test() {
38        let x = -220300isize;
39        assert_eq!(x.format_number(2, ",", "."), "-220,300.00");
40
41        let x = 320300usize;
42        assert_eq!( x.format_number(2, ",", "."), "320,300.00");
43	}
44
45    #[test]
46    fn format_number_float_test() {
47        let x = 123456789.213123f64;
48        assert_eq!(x.format_number(2, ",", "."), "123,456,789.21");
49	}
50    #[cfg(feature = "decimal")]
51    #[test]
52    fn format_number_decimal_test() {
53        let x = rust_decimal::Decimal::new(12345678921, 2);
54        assert_eq!( x.format_number(2, ",", "."), "123,456,789.21");     
55        
56        let x = rust_decimal::Decimal::new(-123456789213, 3);
57        assert_eq!( x.format_number(2, ",", "."), "-123,456,789.21"); 
58	}
59}