From 227bb0a3ce364ac616b01edf094ad243a7077c40 Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Wed, 19 Oct 2022 11:06:17 +0100 Subject: [PATCH] =?UTF-8?q?Ensure=20database=20doesn=E2=80=99t=20panic=20w?= =?UTF-8?q?hen=20rounding=20decimal=20values=20with=20more=20than=2016=20d?= =?UTF-8?q?ecimal=20places?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #1378 --- lib/src/sql/number.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/lib/src/sql/number.rs b/lib/src/sql/number.rs index 736a2c7d..5af6c8ec 100644 --- a/lib/src/sql/number.rs +++ b/lib/src/sql/number.rs @@ -285,7 +285,14 @@ impl Number { match self { Number::Int(v) => v.into(), Number::Float(v) => v.ceil().into(), - Number::Decimal(v) => (v + BigDecimal::from_f32(0.5).unwrap()).round(0).into(), + Number::Decimal(v) => { + if v.digits() > 16 { + let v = (v.to_f64().unwrap_or_default() + 0.5).round(); + BigDecimal::from_f64(v).unwrap_or_default().into() + } else { + (v + BigDecimal::from_f32(0.5).unwrap()).round(0).into() + } + } } } @@ -293,7 +300,14 @@ impl Number { match self { Number::Int(v) => v.into(), Number::Float(v) => v.floor().into(), - Number::Decimal(v) => (v - BigDecimal::from_f32(0.5).unwrap()).round(0).into(), + Number::Decimal(v) => { + if v.digits() > 16 { + let v = (v.to_f64().unwrap_or_default() - 0.5).round(); + BigDecimal::from_f64(v).unwrap_or_default().into() + } else { + (v - BigDecimal::from_f32(0.5).unwrap()).round(0).into() + } + } } } @@ -301,7 +315,14 @@ impl Number { match self { Number::Int(v) => v.into(), Number::Float(v) => v.round().into(), - Number::Decimal(v) => v.round(0).into(), + Number::Decimal(v) => { + if v.digits() > 16 { + let v = v.to_f64().unwrap_or_default().round(); + BigDecimal::from_f64(v).unwrap_or_default().into() + } else { + v.round(0).into() + } + } } }