Skip to content

Commit

Permalink
Fixes integer handling in Decimal::to_f64 by expanding range (#443)
Browse files Browse the repository at this point in the history
  • Loading branch information
anatols committed Nov 25, 2021
1 parent 9b6a1ce commit 2f2d0fb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
5 changes: 4 additions & 1 deletion src/decimal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2090,7 +2090,10 @@ impl ToPrimitive for Decimal {

fn to_f64(&self) -> Option<f64> {
if self.scale() == 0 {
let integer = self.to_i64();
// If scale is zero, we are storing a 96-bit integer value, that would
// always fit into i128, which in turn is always representable as f64,
// albeit with loss of precision for values outside of -2^53..2^53 range.
let integer = self.to_i128();
integer.map(|i| i as f64)
} else {
let sign: f64 = if self.is_sign_negative() { -1.0 } else { 1.0 };
Expand Down
10 changes: 6 additions & 4 deletions tests/decimal_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2570,9 +2570,10 @@ fn it_converts_to_f64() {
"2.1234567890123456789012345678",
Some(2.1234567890123456789012345678_f64),
),
("21234567890123456789012345678", Some(21234567890123458000000000000_f64)),
(
"21234567890123456789012345678",
None, // Cannot be represented in an f64
"-21234567890123456789012345678",
Some(-21234567890123458000000000000_f64),
),
("1.59283191", Some(1.59283191_f64)),
("2.2238", Some(2.2238_f64)),
Expand Down Expand Up @@ -2600,9 +2601,10 @@ fn it_converts_to_f64_try() {
"2.1234567890123456789012345678",
Some(2.1234567890123456789012345678_f64),
),
("21234567890123456789012345678", Some(21234567890123458000000000000_f64)),
(
"21234567890123456789012345678",
None, // Cannot be represented in an f64
"-21234567890123456789012345678",
Some(-21234567890123458000000000000_f64),
),
("1.59283191", Some(1.59283191_f64)),
];
Expand Down

0 comments on commit 2f2d0fb

Please sign in to comment.