代码评审——double与int类型的比较

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

问题描述

在开发过程中经常会遇到两种不同类型数据的比较。本文将以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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值