rspec/rules/S2111/java/rule.adoc

77 lines
2.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Because of floating point imprecision, you're unlikely to get the value you expect from the ``++BigDecimal(double)++`` constructor.
From http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(double)[the JavaDocs]:
____
The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
____
Instead, you should use ``++BigDecimal.valueOf++``, which uses a string under the covers to eliminate floating point rounding errors, or the constructor that takes a ``++String++`` argument.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
double d = 1.1;
BigDecimal bd1 = new BigDecimal(d); // Noncompliant; see comment above
BigDecimal bd2 = new BigDecimal(1.1); // Noncompliant; same result
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
double d = 1.1;
BigDecimal bd1 = BigDecimal.valueOf(d);
BigDecimal bd2 = new BigDecimal("1.1"); // using String constructor will result in precise value
----
== Resources
2021-04-28 16:49:39 +02:00
* https://wiki.sei.cmu.edu/confluence/x/kzdGBQ[CERT, NUM10-J.] - Do not construct BigDecimal objects from floating-point literals
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use "BigDecimal.valueOf" instead.
'''
== Comments And Links
(visible only on this page)
=== on 7 Oct 2014, 16:24:30 Nicolas Peru wrote:
\[~ann.campbell.2] we might want to refer or quote the JavaDoc of BigDecimal double constructor here : \http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#BigDecimal(double)
=== on 10 Oct 2014, 15:13:53 Freddy Mallet wrote:
Perfect !
=== on 16 Jan 2015, 09:32:59 Sébastien Gioria wrote:
Coudl be tag "security" as it's part of the CERT Secure Coding for Java (\https://www.securecoding.cert.org/confluence/display/java/NUM10-J.+Do+not+construct+BigDecimal+objects+from+floating-point+literals)
=== on 19 Jan 2015, 08:42:15 Ann Campbell wrote:
Thanks [~sebastien.gioria], reference added!
=== on 14 Jul 2016, 16:04:49 Ann Campbell wrote:
https://github.com/google/error-prone/blob/master/docs/bugpattern/BigDecimalLiteralDouble.md
endif::env-github,rspecator-view[]