Please don't fail to_f64()
Closed this issue · 2 comments
The code for Decimal::to_f64
will offload to to_i64
if scale is 0, and subsequently fail if the number does not fit. But it seems inconsistent that e.g. 12345678901234567890 will fail to convert, but 12345678901234567890.1 converts fine (with loss of precision of course).
Would it perhaps be possible to fall through to the alternative branch if the i64 conversion fails? Someone expecting a failure if scale == 0 would probably be using to_i64
in the first place (my guess -- and besides i64 doesn't always convert cleanly to f64 either).
Example program:
use rust_decimal::prelude::*;
fn main() {
let x = Decimal::from_i128_with_scale(12345678901234567890, 0);
let y = x + Decimal::new(1, 1);
println!("x = {:?} y = {:?}", x.to_f64(), y.to_f64());
}
prints:
x = None y = Some(12345678901234567000.0)
Happy to submit a PR but it's very small change:
if self.scale() == 0 {
if let Some(integer) = self.to_i64() {
return integer as f64;
}
}
... // continue else branch
Yeah, I agree - this is weird behavior and appears to be a bug. Happy to accept a PR with some tests supporting the feature!