Given a fastnum decimal number, how to convert it to a primitive integer like usize? The fastnum source file to_primitive.rs contains a mention of:
to_uint_impl!(to_usize, usize);
But when I try to use it as in the following:
use fastnum::{dec256};
fn main() {
let a = dec256!(10);
let b = a.to_usize();
println!("{}", b);
}
It gives this error message:
error[E0599]: no method named `to_usize` found for struct `Decimal` in the current scope
--> src\main.rs:5:15
|
5 | let b = a.to_usize();
| ^^^^^^^^ method not found in `Decimal<4>`
What am I missing?
There is a TryFrom<Decimal<N>> for usize implementation available:
use fastnum::dec256;
fn main() {
let a = dec256!(10);
let b = usize::try_from(a);
println!("{:?}", b);
let a = dec256!(-10);
let b = usize::try_from(a);
println!("{:?}", b);
}
Ok(10)
Err(PosOverflow)
The .to_usize() method is provided via the ToPrimitive trait implementation which is from the num-traits crate. To use it, you would need to enable the "numtraits" feature and import the trait:
[dependencies]
fastnum = { version = "0.2.2", features = ["numtraits"] }
num-traits = "0.2.19"
use fastnum::dec256;
use num_traits::ToPrimitive;
fn main() {
let a = dec256!(10);
let b = a.to_usize();
println!("{:?}", b);
}
Some(10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With