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
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())
    }
}

/// The value is interpreted as the smallest possible amount, so 1 would be 0.01
impl<L> From<usize> for Currency<L>
where
    L: CurrencyLocale + Default,
{
    fn from(value: usize) -> Self {
        Self::new(false, value, L::default())
    }
}

/// The value is interpreted as the smallest possible amount, so 1 would be 0.01
impl<L> From<isize> for Currency<L>
where
    L: CurrencyLocale + Default,
{
    fn from(value: isize) -> Self {
        Self::new(value.is_negative(), value.abs() as usize, L::default())
    }
}