What is the best way to be aware of the loss of precision when converting a usize to a f64 in Rust? -
this code:
use std::usize; fn main() { fn main() { let = usize::max; println!("{:?}", ); println!("{:?}", f64 ); }
returns
18446744073709551615 18446744073709552000
what best way aware of loss of precision?
the conv
crate designed handle this. valuefrom
/valueinto
traits perform value-preserving conversions return error if input value cannot represented in output type. example:
/*! add `cargo.toml`: ```cargo [dependencies] conv = "0.3.2" ``` */ extern crate conv; use conv::prelude::*; fn main() { let = std::u32::max; println!("u32::max -> f32: {:?}", a.value_as::<f32>()); println!("u32::max -> f64: {:?}", a.value_as::<f64>()); }
outputs:
u32::max -> f32: err(posoverflow(..)) u32::max -> f64: ok(4294967295)
alternately, can replicate checking conv
hand: check input integer not fall outside range of integers floating point type can represent. specifically:
f32
: ±16,777,215f64
: ±9,007,199,254,740,991
Comments
Post a Comment