davidlghellin commented on code in PR #10509:
URL: https://github.com/apache/arrow-rs/pull/10509#discussion_r4176963245
##########
arrow-cast/src/cast/mod.rs:
##########
@@ -92,7 +100,124 @@ where
D: DecimalType,
F: Fn(D::Native) -> f64,
{
- f(x) / 10_f64.powi(scale)
+ let unscaled = f(x);
+ // Both operands are exact in this range, so this rounds once. A negative
scale
+ // multiplies, since `10^-scale` is the exact power of ten there.
+ if (-22..=22).contains(&scale) && unscaled.abs() < F64_EXACT_INT_LIMIT {
+ return if scale >= 0 {
+ unscaled / 10_f64.powi(scale)
+ } else {
+ unscaled * 10_f64.powi(-scale)
+ };
+ }
+ match i8::try_from(scale) {
+ Ok(scale) => decimal_to_f64_rounded_once::<D>(x, scale, unscaled),
+ Err(_) => unscaled / 10_f64.powi(scale),
+ }
+}
+
+/// Rounds once for the values the arithmetic cannot convert exactly, by
parsing
+/// the decimal's own text.
+#[cold]
+#[inline(never)]
+fn decimal_to_f64_rounded_once<D: DecimalType>(x: D::Native, scale: i8,
unscaled: f64) -> f64 {
+ D::format_decimal(x, u8::MAX, scale)
+ .parse::<f64>()
+ .unwrap_or_else(|_| unscaled / 10_f64.powi(scale.into()))
Review Comment:
Agreed, it isn't reachable — format_decimal always writes a decimal literal.
Added a note saying so; kept the fallback only to avoid a panic there. Happy to
drop it along with the string parsing in the followup.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]