[
https://issues.apache.org/jira/browse/CASSANDRA-18647?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17740047#comment-17740047
]
Nadav Har'El commented on CASSANDRA-18647:
------------------------------------------
By the way, there is a unit test - testNumericCastsInSelectionClause in
test/unit/org/apache/cassandra/cql3/functions/CastFctsTest.java - that should
have caught this bug. The problem is that it compares the result of the cast
not to any specific value but to BigDecimal.valueOf(5.2F), and this
BigDecimal.valueOf(float) is apparently the same function that the Cassandra
implementation uses for this purpose, so if the implementation has a bug the
test doesn't verify anything.
I think I know the cause of this bug. It turns out that BigDecimal does *not*
have a float overload, only a double. The Java documentation says that:
valueOf(double val) Translates a double into a BigDecimal, using the double's
canonical string representation provided by the Double.toString(double) method.
So the solution of how to turn a float into a Decimal is easy - just use
*Float.toString(float)* and then construct a BigDecimal using that string - not
using the float.
So it seems the fix would be a two-line patch to getDecimalConversionFunction()
in src/java/org/apache/cassandra/cql3/functions/CastFcts.java to do that.
> CASTing a float to decimal adds wrong digits
> --------------------------------------------
>
> Key: CASSANDRA-18647
> URL: https://issues.apache.org/jira/browse/CASSANDRA-18647
> Project: Cassandra
> Issue Type: Bug
> Reporter: Nadav Har'El
> Priority: Normal
>
> If I create a table with a *float* (32-bit) column, and cast it to the
> *decimal* type, the casting wrongly passes through the double (64-bit) type
> and picks up extra, wrong, digits. For example, if we have a column e of type
> "float", and run
> INSERT INTO tbl (p, e) VALUES (1, 5.2)
> SELECT CAST(e AS decimal) FROM tbl WHERE p=1
> The result is the "decimal" value 5.199999809265137, with all those extra
> wrong digits. It would have been better to get back the decimal value 5.2,
> with only two significant digits.
> It appears that this happens because Cassandra's implementation first
> converts the 32-bit float into a 64-bit double, and only then converts that -
> with all the silly extra digits it picked up in the first conversion - into a
> "decimal" value.
> Contrast this with CAST(e AS text) which works correctly - it returns the
> string "5.2" - only the actual digits of the 32-bit floating point value are
> converted to the string, without inventing additional digits in the process.
--
This message was sent by Atlassian Jira
(v8.20.10#820010)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]