Reason

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.

// This will print 0.6100000000000001

System.out.println(1.03 - .42);

// This will print 0.09999999999999998

System.out.println(1.00 - 9 * .10);

Right way

Use BigDecimal , int , or long for monetary calculations

public static void main(String[] args) {

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 + " items bought.");

System.out.println("Money left over: $" + funds);

}

Advantage

  1. Precise
  2. Full control over Rounding(Able to select from eight rounding modes whenever an operation that entails rounding is performed)

Disadvantage

  1. less convenient than using a primitive arithmetic type
  2. It's slower

An alternative to using BigDecimal

Using int or long, depending on the amounts involved, and to keep track of the decimal point yourself.

public static void main(String[] args) {

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");

}

Decision on choosing implementation

Quantities

9

18

>18

Use

int

long

BigDecimal

Summary

Don't use float or double for any calculations that require an exact answer. Use BigDecimal if you want the system to keep track of the decimal point and you don't mind the inconvenience and cost of not using a primitive type.

Effective Java 48 Avoid float and double if exact answers are required的更多相关文章

  1. java中int,float,long,double取值范围,内存泄露

    java中int,float,long,double取值范围是多少? 写道 public class TestOutOfBound { public static void main(String[] ...

  2. Java中的float、double计算精度问题

    java中的float.double计算存在精度问题,这不仅仅在java会出现,在其他语言中也会存在,其原因是出在IEEE 754标准上. 而java对此提供了一个用于浮点型计算的类——BigDeci ...

  3. 【转】JAVA程序中Float和Double精度丢失问题

    原文网址:http://blog.sina.com.cn/s/blog_827d041701017ctm.html 问题提出:12.0f-11.9f=0.10000038,"减不尽" ...

  4. Effective Java 50 Avoid strings where other types are more appropriate

    Principle Strings are poor substitutes for other value types. Such as int, float or BigInteger. Stri ...

  5. Effective Java 67 Avoid excessive synchronization

    Principle To avoid liveness and safety failures, never cede control to the client within a synchroni ...

  6. java 小心使用float和double他可能不如你所想

    public static void main(String[] args) { double funds=1.00; ; // ; ;funds>=price;price+=.){ funds ...

  7. Effective Java 07 Avoid finallizers

    NOTE Never do anything time-critical in a finalizer. Never depend on a finalizer to update critical ...

  8. Effective Java 73 Avoid thread groups

    Thread groups were originally envisioned as a mechanism for isolating applets for security purposes. ...

  9. Effective Java 05 Avoid creating unnecessary objects

    String s = new String("stringette"); // Don't do this. This will create an object each tim ...

随机推荐

  1. [python]初探socket

    1.什么是socket? Socket中文译作:套接字,但是大家一般约定俗称的都用:socket.我想在解释socket是什么之前,先说它是用来干嘛的:socket是来建立'通信'的基础,建立连接,传 ...

  2. [Python]同是新手的我,分享一些经验

    本来想分享一些知识,但是发现,写着写着,感觉分享一些经验,或许会少让大家走一些弯路,索性就把标题一改. 我不是教给大家些什么,我没有资格,我也是摸着石头过河,我只是本着分享的精神,在这里分享自己的东西 ...

  3. 手把手教你从购买vps到搭建一个node服务器

    要准备什么? 1.5刀 2.最好有FQ软件(可以用蓝灯) let's Go! 一.vps购买 vps可以选择digital ocean(do) 链接 ,由于是外国网站,响应比较慢,所以最好翻个墙. g ...

  4. C++中指针和引用的区别

    ①指针可以为空,引用不能为空: ②指针可以被赋值,引用必须在声明时赋值,之后不能被赋值: ③指针可以指向堆中空间,引用不能指向堆中空间,如int &p=new int; 会编译出错.

  5. 【第三课】ANR和OOM——贪快和贪多的后果(上)

    恼人的ANR 早先年用Android的时候,就连很多知名的app也总是莫名其妙崩溃,好像手机快的时候会崩溃,手机卡的时候app会卡死.卡死的时候会弹出来一个框,询问是要结束app还是继续等待.这就是A ...

  6. 【循序渐进学Python】8.面向对象的核心——类型(下)

    1 构造和初始化对象 __init__方法是Python内建众多魔法方法(什么是魔法方法?)中最常见的一个,通过这个方法我们可以定义一个对象的初始操作.当构造函数被调用的时候的任何参数都会传递给__i ...

  7. Winfrom中ListBox绑定List数据源更新问题

    Winfrom中ListBox绑定List数据源更新问题 摘自:http://xiaocai.info/2010/09/winform-listbox-datasource-update/ Winfr ...

  8. cURL和HTTPie

    http://lingxiankong.github.io/blog/2014/08/19/curl-httpie/ 前两天在网上看到一个号称比cURL更牛逼的命令行工具HTTPie,提供命令行交互方 ...

  9. python flask应用部署

    失败版本:flask+uwsgi ini配置文件 [uwsgi] callable = app ;//程序内启用的application变量名 home = /home/jcuan/code/pyth ...

  10. jQuery中的效果函数方法整理

    注:以下所有的speed 参数可选,规定效果的时长.它可以取以下值:"slow"."fast" 或毫秒. 以下所有的callback 参数可选,是效果完成后所执 ...