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+selenium+unittest,爬虫电影网站

    以前经常在这个网站上下载电影下来看,这个网站比较坑的就是,主页上只有电影的名称,但是评分是看不到的:只有再点击电影名字,进入电影主页时才能看到评分.一般下载的电影都是评分高的才看,低的就忽略掉了.每次 ...

  2. AEAI EM费用管理系统V1.0.2版本开源发布

    本次开源发布是AEAI EM费用管理系统 V1.0.2版,该版本是此产品的首个版本,产品现已开源并上传至开源社区http://www.oschina.net/p/aeai-em. 产品说明: AEAI ...

  3. Azure开发者任务之二:Cloud Service项目添加到ASP.Net Web中

    假设我们正在把现有的Web应用程序或ASP.Net MVC Web应用程序迁移到云中.在这种情况下,我们需要把云服务添加到现有的Web应用程序或ASP.Net MVC Web应用程序中. 我们有一个W ...

  4. C#函数、参数数组(例子)★

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  5. 看了一本Unity3D的教程

    国内写的<Unity 3D游戏开发>. 实例挺多,对于有基础的人来说,上手会挺快的: 但进阶的东西没有涉及,可能与书的定位有关吧

  6. 比较偏门的JVM语言Quercus - PHP on JVM

    其实,我不确定Quercus是否可以被认定为一门JVM语言:其次Quercus这个东东分开源版与商业版,开源版只能解释执行.而商业版能编译成Java字节码. 但我知道国内,阿里巴巴很早就在使用它,当然 ...

  7. [PE结构分析] 8.输入表结构和输入地址表(IAT)

    在 PE文件头的 IMAGE_OPTIONAL_HEADER 结构中的 DataDirectory(数据目录表) 的第二个成员就是指向输入表的.每个被链接进来的 DLL文件都分别对应一个 IMAGE_ ...

  8. PHP KMP算法实现

    function getNext( $str ){ $ret = array(0=>0); for( $j =1; $j < strlen($str); $j++ ){ $_s = sub ...

  9. 自制javascript游戏-点燃火绳

    自制javascript游戏-点燃火绳 这是一款多关卡的游戏,目录有21个地图,游戏采纯原生 js库JY编写,所以编写得很简单迅速,这款游戏的思路来源于,一个人撸管太多,手会不会连鼠标也拿不稳,为了验 ...

  10. ASP.NET检测到有潜在危险的 Request.Form 值解决方案汇总

    ASP.NET检测到有潜在危险的 Request.Form 值解决方案汇总 当我们在网站中使用CKEditor等富文本编辑器时,大多都会遇到这样的到警告 这是因为ASP.NET默认开启对页面提交内容的 ...