问题描述
在开发过程中经常会遇到两种不同类型数据的比较。本文将以double和int类型的比较进行讨论。
首先用以下代码进行举例:
double value= 1.00;
int intValue = (int) value;
String result = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
此时,当使用静态代码扫描工具时,会提示以下信息:

原因分析:
静态代码分析工具提供的分析:
Floating point math is imprecise because of the challenges of storing such values in a binary representation. Even worse, floating point math is not associative; push a float or a double through a series of simple mathematical operations and the answer will be different based on the order of those operation because of the rounding that takes place at each step.
Therefore, the use of the equality (==) and inequality (!=) operators on float or double values is almost always an error. Instead the

本文讨论了开发中double和int类型比较的挑战,指出静态代码分析工具对浮点数不精确性的警告。推荐使用BigDecimal的compareTo()方法进行比较,避免精度误差并演示了实际应用示例。
4163

被折叠的 条评论
为什么被折叠?



