Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert fastnum decimal number to usize

Tags:

rust

fastnum

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?

like image 734
rwallace Avatar asked Oct 26 '25 05:10

rwallace


1 Answers

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)
like image 82
kmdreko Avatar answered Oct 27 '25 19:10

kmdreko