java 中浮点类型常用计算方法

JAVA 浮点类型的计算,我们知道会出现失精的问题,如果程序中经常使用,我的做法是,写一个工具类,专门处理类似问题。

 

	/**
	 * 
	 * @Description:两个double类型相加,返回Double
	 * @createBy:qiqiang ran
	 * @createdate:2012-3-23
	 * @param double d1
	 * @param double d2
	 * @return double
	 */
	public static double doubleAdd(double d1, double d2) {
		BigDecimal a1 = new BigDecimal(d1);
		BigDecimal b1 = new BigDecimal(d2);
		return a1.add(b1).doubleValue();
	}

 

那么用BigDecimal 就完全可以解决了吗?我找到这样一句话:
Note: the results of this constructor can be somewhat unpredictable.
One might assume that new BigDecimal(.1) is exactly equal to .1, 
but it is actually equal to .1000000000000000055511151231257827021181583404541015625. 
This is so because .1 cannot be represented exactly as a double (or, for that
matter, as a binary fraction of any finite length). 
Thus, the long value that is being passed in to the constructor is not exactly 
equal to .1, appearances nonwithstanding. 

The (String) constructor, on the other hand, is perfectly predictable: 

new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, 

it is generally recommended that the (String) constructor be used in preference 

to this one.(转《Effective Java》

我了解了一下,BigDecimal 有4个构造方法,具体的大家可以去看看,这里强调了是着两个:
BigDecimal(String val){...};
BigDecimal(double val){...};
而我们通常使用的是 构造double val,但是从刚才那段说明中得知:字符串的构造函数优先于另一个。
那么我们现在的方法可以这样改进:

 

	/**
	 * 
	 * @Description:两个double类型相加,返回Double
	 * @createBy:qiqiang ran
	 * @createdate:2012-3-23
	 * @param double d1
	 * @param double d2
	 * @return double
	 */
	public static double doubleAdd(double d1, double d2) {
		BigDecimal a1 = new BigDecimal(Double.toString(d1));
		BigDecimal b1 = new BigDecimal(Double.toString(d2));
		return a1.add(b1).doubleValue();
	}
同理可得:我们可以提供相应 - * / 方法,分别对应:.subtract .multiply .div 方法。
注意:运算过程中需要注意参数,以及保留位数,比如:除法运算,里面方法很多,大家可以尝试。 
最后:这个以前就遇到过,只是临时copy 过来用用,老是不明白,
后来自己多写写,多领悟好多了,虽然还有很多不明白的地方,
但是相信自己动手 动脑去完成,总会搞清楚的。也给新入行的人提醒,
最好别一味的copy代码,哪怕是上面两行最简单的代码,写一次就深刻一次,
这也是我不将后面方法写完的原因。还有关于JS 计算也有同样的问题,
大家也可以去研究研究。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值