Closed DrAlta closed 10 months ago
Hi @DrAlta,
We have ToPrimitive
implementation.
use fraction::ToPrimitive;
...
let value: Option<f64> = fraction.to_f64();
Would it be possible to implement the Into<f64>
or From<> for f64
and f32
traits? It would make some generic code I'm writing a lot easier, being able to implement Into<f64>
for all types, where it would also be implemented for fraction types. Just a small QOL improvement :)
Ok, so there is TryInto<f64...>
implemented! Let's say you have a type T that could be a fraction, use like so:
use fraction::{Fraction, Decimal};
struct Sqrt<T> {
s_val: T,
}
impl<T: Clone> TryFrom<&Sqrt<T>> for f64 where f64: TryFrom<T>{
type Error = <f64 as TryFrom<T>>::Error;
fn try_from(value: &Sqrt<T>) -> Result<Self, Self::Error> {
// need to clone to avoid infinite template recursion
match f64::try_from(value.s_val.clone()){
Ok(s_64) => {
Ok(s_64.sqrt())
},
Err(e) => {
Err(e)
}
}
}
}
fn main() -> Result<(), ()>{
let f = Fraction::new(1u8,2u8);
let d = Decimal::from(0.5);
assert_eq!(d.try_into(), Ok(0.5f64));
let f_64: Result<f64, ()> = f64::try_from(f);
let s: &Sqrt<Fraction> = &Sqrt {s_val: Fraction::new(1u8,2u8)};
let s_64: Result<f64, _> = s.try_into();
println!("{:?}", s_64);
let s: &Sqrt<&Sqrt<Fraction>> = &Sqrt{s_val: &Sqrt{s_val: Fraction::new(1u8,16u8)}};
// Ok(s_64)
let s_64: Result<f64, _> = s.try_into();
println!("{:?}", s_64);
Ok(())
}
NOTE: need to install from git like cargo add --git https://github.com/dnsl48/fraction
Hi @feefladder, you are right, that's been implemented in master, but not released yet.
Still finishing the documentation for that. Probably, will go out soon in the 0.15
release.
Thank you for raising this subject.
std::convert::TryFrom
is now implemented as a part of the 0.15.0
release.
Some of the examples in the readme were updated to reflect the new functionality.
Converting into float is now possible vie GenericFraction::try_into::<f64>()
or f64::try_from(GenericFraction)
.
I remember having this problem before but I can't remember my solution.
Could we impl Into of something?
I feel like just using
format!("x:.9}").parse::<f32>().unwrap()