linhongliu-db opened a new pull request, #60413: URL: https://github.com/apache/spark/pull/60413
### What changes were proposed in this pull request? `Decimal.roundToNumeric` (used by `roundToInt`/`roundToShort`/`roundToByte`) handles the compact `longVal` case exactly, but for a BigDecimal-backed DECIMAL (precision > 18) it converts to a `Double` first and then range-checks and truncates. Going through a `Double` rounds values such as `0.999999999999999999` up to `1` before truncating, and makes values just inside the INT range (for example `2147483647.999999999999`) overflow. `roundToLong` already avoids this via `toBigInteger.longValueExact()`. This PR truncates the exact value toward zero for the BigDecimal case (with an exact range check) in both the interpreted and codegen ANSI cast paths. A new conf `spark.sql.legacy.castDecimalToIntegralTypeViaDouble` (default `false`) restores the previous behavior. ### Why are the changes needed? Wrong results and spurious overflows when ANSI-casting a wide DECIMAL to `TINYINT`/`SMALLINT`/`INT`. ### Does this PR introduce _any_ user-facing change? Yes, documented in `docs/sql-migration-guide.md`. `CAST(0.999999999999999999BD AS INT)` now returns `0` instead of `1`, and a value just inside the target range no longer overflows. Set `spark.sql.legacy.castDecimalToIntegralTypeViaDouble=true` to restore the old behavior. ### How was this patch tested? New `CastWithAnsiOnSuite` test covering both the interpreted and codegen paths (exact truncation and, under the legacy conf, the Double-based path). Locally the ANSI-on, ANSI-off and TryCast suites (437 tests) pass and scalastyle is clean on JDK 21. ### Was this patch authored or co-authored using generative AI tooling? Generated-by: Claude Code (Isaac) This pull request and its description were written by Isaac. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
