[读书笔记][Effective Java]不要在精确计算中使用float和double类型

在精确计算,尤其是有关金钱的商业运算中,不能使用floatdouble类型。

 

看如下的例子:

商店里某种糖果的价格是0.1元,0.2元,0.3元, …… 依此类推,一直到1.00元。现在你手中有1元钱。你想买一些糖果,假设你从1角的糖果开始依次买,一种价格的买一颗。计算一下一共可以买多少颗糖果,最后会剩下多少零钱。

 

第一个程序:

package com.mytest;

public class Test {
 private static final double FUNDS = 1.00;
 private static final double TEN_CENTS = .1;
 
    public static void main( String[] args ) {
     int itemsBought = 0;
     double myfund = FUNDS;
     for (double price = TEN_CENTS; price < myfund; price+= TEN_CENTS) {
   itemsBought++;
   myfund-= price;
  }
     
     System.out.println("itemsBought: " + itemsBought);
     System.out.println("myfund left: " + myfund);
    }
}

在这里,使用double类型,进行计算,但是却得到如下结果:

itemsBought: 3
myfund left: 0.3999999999999999

这并不是正确的结果。在涉及金钱的运算中,应该使用BigDecimal。

正确的程序如下:

package com.mytest;

import java.math.BigDecimal;

public class Test {
 private static final BigDecimal FUNDS = new BigDecimal("1.00");
 private static final BigDecimal TEN_CENTS = new BigDecimal(".10");
 
    public static void main( String[] args ) {
     int itemsBought = 0;
     BigDecimal myfund = FUNDS;
     for (BigDecimal price = TEN_CENTS; price.compareTo(myfund) <= 0; price = price.add(TEN_CENTS)) {
   itemsBought++;
   myfund = myfund.subtract(price);
  }
     
     System.out.println("itemsBought: " + itemsBought);
     System.out.println("change: " + myfund);
    }
}

打印结果:

itemsBought: 4
change: 0.00

这才是正确的答案。

In summary, don't use float or double for any calculations that require an exact answer.  User BigDecimal if you want the system to keep track of the decimal point and you don't mind the inconveneice of not using a primitive type.  Using BigDecimal has the added advantage that it gives you full controll over rounding, letting you select from eight rounding modes whenever an operation that entails rounding is performed.  This comes in handy if you're performing business calculations with legally mandated rounding behaviour.  If performance is of the essence, if you don't mind keeping track of the decimal point yourself, and if the quantities aren't too big, use int or long.  If the quantitiest don't exceed nine decimal digits, you can use int; if they don't exceed eighteen digits, you can use long.  If the quantities exceed eighting digits, you must use BigDecimal.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值