akubera / bigdecimal-rs

Arbitrary precision decimal crate for Rust
Other
302 stars 73 forks source link

round method works incorrectly for zero decimal places #136

Closed ice1080 closed 1 month ago

ice1080 commented 1 month ago

The .round(round_digits) method does not work for rounding to zero decimal places.

let unrounded = BigDecimal::from_str("-0.68")?;
println!("{}", unrounded.round(0));
// output is 1 -- incorrect
println!("{}", unrounded.with_scale_round(0, RoundingMode::HalfUp));
// output is -1 -- correct

I do recognize that the docs for round specify that it is used for rounding to round_digits after the decimal point, but it seems confusing that a round method doesn't work for round_digits less than 1.

Return number rounded to round_digits precision after the decimal point

Shouldn't round work the same as with_scale_round just using the default rounding mode?

danilopedraza commented 1 month ago

I think is because of this line:

return BigDecimal::new(BigInt::one(), round_digits);

It doesn't take the sign into account.

danilopedraza commented 1 month ago

Put a fix in #137

akubera commented 1 month ago

Fix has been merged in #137.

Your solution was correct: round has been reimplemented as with_scale_round(scale, <DEFAULT-ROUNDING-MODE>)

On the subject of rounding, I have a commit here with new methods for Context and BigDecimalRef, if anyone has ideas for any particularly convenient methods which should be added, let me know:

https://github.com/akubera/bigdecimal-rs/commit/d7e8691e6d53ad9de78f83a87dff76914c4d093c