Avoid float and double types if exact answers are required.

本文讨论了在货币计算中使用float和double的局限性,并提供了使用BigDecimal、int和long的指导原则。通过一个具体例子展示了如何正确地进行货币计算,避免了精度损失的问题。

Don't use float or double for any calculations that require an exact answer.

The float and double types are particularly ill-suited for monetary calculations

because it is impossible to represent 0.1(or any other negative power of ten) as a float or double exactly.

Use BigDecimal, int or long for monetary calculations.

Use BigDecimal if you want the system to keep track of the decimal point and you don't mind the inconvenience of not using a primitive type.

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 quantities 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 eighteen digits, you must use BigDecimal.


Here is an example:


import java.math.BigDecimal;


public class Test1 {
    public static void main(String args[]) {
        
        System.out.println("method test1() executed!");
        test1();
        
        System.out.println("method test2() executed!");
        test2();
        
        System.out.println("method test3() executed!");
        test3();
    }
    public static void test1() {
        double funds = 1.00;
        int itemsBought = 0;
        for (double price = .10; funds >= price; price += .10) {
            funds -= price;
            itemsBought++;
        }
        System.out.println(itemsBought + " itmes bought.");
        System.out.println("Change: $" + funds);

    }
    public static void test2(){
        final BigDecimal TEN_CENTS = new BigDecimal(".10");
        int itemsBought = 0;
        BigDecimal funds = new BigDecimal("1.00");
        for (BigDecimal price = TEN_CENTS; funds.compareTo(price) >= 0; price = price.add(TEN_CENTS)){
            itemsBought++;
            funds = funds.subtract(price);
        }
        System.out.println(itemsBought + " itmes bought.");
        System.out.println("Change: $" + funds);
    }
    
    public static void test3() {
        int itemsBought = 0;
        int funds = 100;
        for (int price = 10; funds >= price; price += 10) {
            itemsBought++;
            funds -= price;
        }
        System.out.println(itemsBought + " items bought." );
        System.out.println("Money left over: " + funds + " cents");
    }
}


Result:


method test1() executed!
3 itmes bought.
Change: $0.3999999999999999


method test2() executed!
4 itmes bought.
Change: $0.00


method test3() executed!
4 items bought.
Money left over: 0 cents


Comment:

the result of  test1()  is the Wrong answer!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值