[ 
https://issues.apache.org/jira/browse/SPARK-60843?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
 ]

Max Gekk updated SPARK-60843:
-----------------------------
    Affects Version/s: 4.5.0
                           (was: 5.0.0)

> Truncate decimals exactly when casting to INT, SMALLINT and TINYINT
> -------------------------------------------------------------------
>
>                 Key: SPARK-60843
>                 URL: https://issues.apache.org/jira/browse/SPARK-60843
>             Project: Spark
>          Issue Type: Bug
>          Components: SQL
>    Affects Versions: 4.5.0
>            Reporter: Dustin Smith
>            Assignee: Dustin Smith
>            Priority: Major
>              Labels: pull-request-available
>
> {{Decimal.roundToInt}}, {{roundToShort}} and {{roundToByte}}, which back the 
> ANSI and {{try_cast}} casts from {{DECIMAL}} to {{INT}}, {{SMALLINT}} and 
> {{TINYINT}}, convert a BigDecimal-backed value to a {{Double}}, range-check 
> it and return its integer part. When the fraction is close enough to 1 to 
> round up as a double, the cast silently returns a value one too high. With 
> {{spark.sql.ansi.enabled=true}}:
> {code:sql}
> SELECT CAST(CAST('0.999999999999999999' AS DECIMAL(20,18)) AS INT);
> -- returns 1, should return 0 (as the non-ANSI cast does)
> SELECT CAST(CAST('1000000000.9999999999' AS DECIMAL(20,10)) AS INT);
> -- returns 1000000001, should return 1000000000
> {code}
> At the maximum or minimum of the target type the same rounding pushes the 
> value past the bound, so the cast fails even though the truncated result fits:
> {code:sql}
> SELECT CAST(CAST('2147483647.99999999' AS DECIMAL(20,8)) AS INT);
> -- fails with CAST_OVERFLOW, should return 2147483647
> SELECT try_cast(CAST('2147483647.99999999' AS DECIMAL(20,8)) AS INT);
> -- returns NULL, should return 2147483647
> {code}
> When the same value is held as an unscaled long (precision <= 18), the check 
> is already exact, as is {{roundToLong}}, which truncates through 
> {{BigInteger}}. So the result of the cast depends on the internal 
> representation of the value.
> Proposed change: truncate BigDecimal-backed values exactly via 
> {{BigInteger}}, as {{roundToLong}} does, and range-check the truncated 
> integer. Values that are actually out of range still overflow. Add a line to 
> the SQL migration guide.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to