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
use crate::{Currency, CurrencyLocale};

/// Assumes that the f32 is meant as a money value, for example 10.99 would be 10.99
impl<L> From<f32> for Currency<L>
where
    L: CurrencyLocale + Default,
{
    fn from(value: f32) -> Self {
        let val = (value * 100.0).round().trunc().abs() as usize;
        Self::new(value.is_sign_negative(), val, L::default())
    }
}

impl<L> From<Currency<L>> for f32
where
    L: CurrencyLocale + Default,
{
    fn from(value: Currency<L>) -> Self {
        let float = value.amount as f32 / 100.0;
        if value.negative {
            0.0 - float
        } else {
            float
        }
    }
}

/// Assumes that the f64 is meant as a money value, for example 10.99 would be 10.99
impl<L> From<f64> for Currency<L>
where
    L: CurrencyLocale + Default,
{
    fn from(value: f64) -> Self {
        let val = (value * 100.0).round().trunc().abs() as usize;
        Self::new(value.is_sign_negative(), val, L::default())
    }
}

macro_rules! from_unsigned {
    ($x:ty) => (
        impl<L> From<$x> for Currency<L>
        where
            L: CurrencyLocale + Default,
        {
            fn from(value: $x) -> Self {
                Self::new(false, value as usize, L::default())
            }
        }

    );
     ($x:ty, $($y:ty),+) => (
        from_unsigned!($x);
        from_unsigned!($($y),+);
        )
}

macro_rules! from_signed {
    ($x:ty) => (
        impl<L> From<$x> for Currency<L>
        where
            L: CurrencyLocale + Default,
        {
            fn from(value: $x) -> Self {
                Self::new(value.is_negative(), value.abs() as usize, L::default())
            }
        }

    );
     ($x:ty, $($y:ty),+) => (
        from_signed!($x);
        from_signed!($($y),+);
        )
}

from_signed!(i8, i16, i32, i64, isize);
from_unsigned!(u8, u16, u32, u64, usize);