Skip to main content

fastnum/decimal/dec/impls/
to.rs

1use crate::{
2    bint::ParseError,
3    decimal::{dec::convert, Decimal},
4};
5
6type D<const N: usize> = Decimal<N>;
7
8macro_rules! try_to_impl {
9    ($($name:ident $int:ty,)*) => {
10        impl<const N: usize> D<N> {
11            $(
12                #[inline]
13                #[doc = concat!("Converts [Decimal] into [`", stringify!($int), "`].")]
14                pub const fn $name(self) -> Result<$int, ParseError> {
15                    convert::$name(self)
16                }
17            )*
18        }
19
20        $(
21            impl<const N: usize> TryFrom<D<N>> for $int {
22                type Error = ParseError;
23
24                #[inline]
25                fn try_from(d: D<N>) -> Result<$int, Self::Error> {
26                    convert::$name(d)
27                }
28            }
29        )*
30    };
31}
32
33try_to_impl!(
34    to_u8 u8,
35    to_u16 u16,
36    to_u32 u32,
37    to_u64 u64,
38    to_u128 u128,
39    to_usize usize,
40
41    to_i8 i8,
42    to_i16 i16,
43    to_i32 i32,
44    to_i64 i64,
45    to_i128 i128,
46    to_isize isize,
47);
48
49impl<const N: usize> From<D<N>> for f32 {
50    #[inline]
51    fn from(d: D<N>) -> f32 {
52        convert::to_f32(d)
53    }
54}
55impl<const N: usize> From<D<N>> for f64 {
56    #[inline]
57    fn from(d: D<N>) -> f64 {
58        convert::to_f64(d)
59    }
60}
61
62impl<const N: usize> D<N> {
63    /// Converts [Decimal] into [`f32`].
64    pub const fn to_f32(self) -> f32 {
65        convert::to_f32(self)
66    }
67
68    /// Converts [Decimal] into [`f64`].
69    pub const fn to_f64(self) -> f64 {
70        convert::to_f64(self)
71    }
72}