From 328ad4696c4c8e78a4db2e8af611cc5c857a924e Mon Sep 17 00:00:00 2001 From: Paul Mason Date: Wed, 21 Jul 2021 15:15:52 +1200 Subject: [PATCH] Round f64 before final conversion in to_f64 --- src/decimal.rs | 2 +- tests/decimal_tests.rs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/decimal.rs b/src/decimal.rs index c4103efb..f3c343ec 100644 --- a/src/decimal.rs +++ b/src/decimal.rs @@ -1841,7 +1841,7 @@ impl ToPrimitive for Decimal { let frac_f64 = (frac_part as f64) / (precision as f64); let value = sign * ((integral_part as f64) + frac_f64); let round_to = 10f64.powi(self.scale() as i32); - Some(value * round_to / round_to) + Some((value * round_to).round() / round_to) } } } diff --git a/tests/decimal_tests.rs b/tests/decimal_tests.rs index 9607517e..ca59f728 100644 --- a/tests/decimal_tests.rs +++ b/tests/decimal_tests.rs @@ -2457,6 +2457,9 @@ fn it_converts_to_f64() { None, // Cannot be represented in an f64 ), ("1.59283191", Some(1.59283191_f64)), + ("2.2238", Some(2.2238_f64)), + ("2.2238123", Some(2.2238123_f64)), + ("22238", Some(22238_f64)), ]; for &(value, expected) in tests { let value = Decimal::from_str(value).unwrap().to_f64();