rust-num / num-bigint

Big integer types for Rust
Apache License 2.0
540 stars 188 forks source link

From f64 #273

Closed samuelcolvin closed 1 year ago

samuelcolvin commented 1 year ago

Hi, thanks for the crate, it's great.

I need to construct BigInts from f64, is there any willingness to support this? Otherwise, is there any existing implementation I can look at?

I'm aware this would be "fuzzy" for very large numbers, but it would still be helpful, particularly where the input is say 1e30.

youknowone commented 1 year ago

If you don't care about performance, format to string and parsing it again will work. Otherwise, getting bit representation of f64 and take mantissa as int and multiply proper value for matching exponent will be easy to implement.

cuviper commented 1 year ago

You can use FromPrimitive::from_f64 for this: https://docs.rs/num-bigint/latest/num_bigint/struct.BigInt.html#method.from_f64

I'm aware this would be "fuzzy" for very large numbers

It should be precise for that, or at least faithful to the accuracy of f64 itself.

The only thing I would call fuzzy is that the conversion truncates any fractional part, just like float as int primitive conversions. You also lose the floating-point distinction between +0.0 and -0.0.