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. 浅谈java类集框架和数据结构(1)

    在另外一篇博客我简单介绍了java类集框架相关代码和理论. 这一篇博客我主要分析一下各个类集框架的原理以及源码分析. 一:先谈谈LinkedList 这是LinkedList源码的开头,我们能看到几点 ...

  2. SQL Server 存储(8/8):理解数据文件结构

    这段时间谈了很多页,现在我们可以看下这些页在数据文件里是如何组织的. 我们都已经知道,SQL Server把数据文件分成8k的页,页是IO的最小操作单位.SQL Server把数据文件里的第1页标记为 ...

  3. UWP开发入门(十四)—— UserControl中Adaptive UI的小技巧

    本篇我们通过绘制一个非常简单的UserControl控件,来分享一下对Adaptive UI的理解及一些图形绘制的技巧. 现在流行的APP都少不了精致的用户头像,首先假设我们需要绘制如下的图形作为默认 ...

  4. mysql update中需要根据条件列更新写法update case

    以下两条语句是否可以合并成一条: where b>'2015-10-12'; , e='2015-01-01' where b='2015-10-12'; 既然来写博客了,那答案肯定是可以的, ...

  5. Vector Clock/Version Clock

    physical clock 机器上的物理时钟,不同的机器在同一个时间点取到的physical clock不一样,之间会存在一定的误差,NTP可以用来控制这个误差,同一个机房内的机器之间的时钟误差可以 ...

  6. 【循序渐进学Python】1. Python基础知识

    1. Python安装和配置 首先需要到Python的官方网站(http://www.python.org/getit/) 下载安装包,现在Python的发行版分为兼容之前Python程序的Pytho ...

  7. 备份和还原SQL Server及压缩Access数据库

    功能说明:备份和恢复SQL Server数据库 * 作者: 刘功勋; * 版本:V0.1(C#2.0);时间:2007-1-1 * 当使用SQL Server时,请引用 COM组件中的,SQLDMO. ...

  8. 重新想象 Windows 8.1 Store Apps (92) - 其他新特性: CoreDispatcher, 日历, 自定义锁屏系列图片

    [源码下载] 重新想象 Windows 8.1 Store Apps (92) - 其他新特性: CoreDispatcher, 日历, 自定义锁屏系列图片 作者:webabcd 介绍重新想象 Win ...

  9. OMG 在线思维导图都有开源的

    my-mind在线思维导图 源代码: https://github.com/ondras/my-mind 演示地址: http://my-mind.github.io/ 试了一下,操作上还有些bug, ...

  10. 在Eclipse中配置Tomcat时,出现Cannot create a server using the selected type错误

    在eclipse中配置Tomcat时,出现Cannot create a server using the selected type错误 原因:Tomcat被删除或者是重新安装,并且安装目录改变了. ...