Skip to content

Commit

Permalink
Add decimal to float conversions.
Browse files Browse the repository at this point in the history
  • Loading branch information
timothee-haudebourg committed Mar 4, 2024
1 parent b84a13e commit 5a094dd
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion src/value/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{borrow::Borrow, collections::HashSet};
use lazy_static::lazy_static;
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{Signed, Zero};
use num_traits::{Signed, ToPrimitive, Zero};
use once_cell::unsync::OnceCell;

use crate::lexical::LexicalFormOf;
Expand Down Expand Up @@ -264,6 +264,22 @@ impl Decimal {
self.lexical
.get_or_init(|| decimal_lexical_representation(&self.data).unwrap())
}

pub fn as_f64(&self) -> Option<f64> {
self.data.to_f64()
}

pub fn as_f32(&self) -> Option<f32> {
self.data.to_f32()
}

pub fn as_float(&self) -> Option<Float> {
self.as_f32().map(Float::from)
}

pub fn as_double(&self) -> Option<Double> {
self.as_f64().map(Double::from)
}
}

impl fmt::Display for Decimal {
Expand Down Expand Up @@ -369,6 +385,38 @@ pub struct FromDecimalError;

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

impl TryFrom<Decimal> for f32 {
type Error = FromDecimalError;

fn try_from(value: Decimal) -> Result<Self, Self::Error> {
value.as_f32().ok_or(FromDecimalError)
}
}

impl TryFrom<Decimal> for Float {
type Error = FromDecimalError;

fn try_from(value: Decimal) -> Result<Self, Self::Error> {
value.as_float().ok_or(FromDecimalError)
}
}

impl TryFrom<Decimal> for f64 {
type Error = FromDecimalError;

fn try_from(value: Decimal) -> Result<Self, Self::Error> {
value.as_f64().ok_or(FromDecimalError)
}
}

impl TryFrom<Decimal> for Double {
type Error = FromDecimalError;

fn try_from(value: Decimal) -> Result<Self, Self::Error> {
value.as_double().ok_or(FromDecimalError)
}
}

impl From<BigInt> for Decimal {
#[inline(always)]
fn from(value: BigInt) -> Self {
Expand Down

0 comments on commit 5a094dd

Please sign in to comment.