Skip to main content

console_tech_money/
lib.rs

1use std::fmt;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub struct Money {
5    cents: i64, 
6}
7
8impl Money {
9    // Construtor:  f64, i64 or &str
10    pub fn new<T>(value: T) -> Self where T: Into<MoneyValue>, {
11        let cents = match value.into() {
12            MoneyValue::Float(f) => (f * 100.0).round() as i64,
13            MoneyValue::Int(i) => i * 100,
14        };
15        Money { cents }
16    }
17
18    pub fn add(&self, other: Money) -> Money {
19        Money {
20            cents: self.cents + other.cents,
21        }
22    }
23
24    pub fn subtract(&self, other: Money) -> Money {
25        Money {
26            cents: self.cents - other.cents,
27        }
28    }
29
30
31    pub fn multiply(&self, factor: f64) -> Money {
32        Money {
33            cents: ((self.cents as f64) * factor).round() as i64,
34        }
35    }
36
37    pub fn divide(&self, divisor: f64) -> Money {
38        Money {
39            cents: ((self.cents as f64) / divisor).round() as i64,
40        }
41    }
42
43    pub fn get_cents(&self) -> i64 {
44        self.cents
45    }
46
47    pub fn get_value(&self) -> f64 {
48        self.cents as f64 / 100.0
49    }
50}
51
52impl fmt::Display for Money {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        write!(f, "R${:.2}", self.get_value())
55    }
56}
57
58// Aux convert using enum
59pub enum MoneyValue {
60    Float(f64),
61    Int(i64),
62}
63
64impl From<f64> for MoneyValue {
65    fn from(v: f64) -> Self {
66        MoneyValue::Float(v)
67    }
68}
69
70impl From<i64> for MoneyValue {
71    fn from(v: i64) -> Self {
72        MoneyValue::Int(v)
73    }
74}
75
76impl From<&str> for MoneyValue {
77    fn from(s: &str) -> Self {
78        MoneyValue::Float(s.parse::<f64>().unwrap_or(0.0))
79    }
80}