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. Html5+css3+angularjs+jquery+webAPi 开发手机web(一)

    前言 随着浏览器的发展 HTML5+CSS3 的使用也越来越广泛,一直想学这个,想学那个折腾下来几乎没学到什么东西.工作经验告诉我,要掌握一门技术,就需要在项目中去磨练, 所以我就准备开发一个手机端的 ...

  2. [Tool] PLSQL使用技巧

    1.PL/SQL Developer保存自定义界面布局 Tools->Preferences->User Interface->Options->Autosave deskto ...

  3. NetworkComms.Net github下载地址

    https://github.com/MarcFletcher/NetworkComms.Net

  4. web api返回格式小结

    web api返回格式小结: 1.默认是返回xml格式数据,如果需要返回json格式,需要在Global.asax中加入: GlobalConfiguration.Configuration.Form ...

  5. 移动web开发总结

    让网页的宽度自适应屏幕<meta name="viewport" content="width=device-width"/>   1)html上加 ...

  6. 字符串与json之间的相互转化

    先在数据库中建表: 再从后台将表取出来,然后转化为json格式,再将其执行ToString()操作后,赋值给前台的隐藏域. 注意引用using Newtonsoft.Json; 前台利用js将隐藏域中 ...

  7. 用SQL语句修复SQL Server数据库

    使用数据库的过程中,由于断电或其他原因,有可能导致数据库出现一些小错误,比如检索某些表特别慢,查询不到符合条件的数据等. 出现这些情况的原因,往往是因为数据库有些损坏,或索引不完整. 在ACCESS中 ...

  8. The type java.util.Map$Entry cannot be resolved. It is indirectly referenced。。.相似的错误

    这个问题是出现一般都是因为JDK版本的问题.今天公司安装NC的时候就出现了这个问题.经过对错误的分析和猜测,将JDK从1.8i换成了1.7,之后就行了.根据我个人的猜测,可能是1.8以后就不支持Map ...

  9. 状态压缩DP---Hie with the Pie

    http: //acm.hust.edu.cn/vjudge/contest/view.action?cid=110044#problem/B Description The Pizazz Pizze ...

  10. 一个web页面的访问的过程

    Browers是如何在浩瀚的互联网上找到我们需要的资源呢? 以下将记录这个过程,这个过程是web编程需要需要熟知的. 用户打开浏览器输入目标地址(比如http://www.sina.com),那么接下 ...