Effective Java 48 Avoid float and double if exact answers are required
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 |
|
Disadvantage |
|
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的更多相关文章
- java中int,float,long,double取值范围,内存泄露
java中int,float,long,double取值范围是多少? 写道 public class TestOutOfBound { public static void main(String[] ...
- Java中的float、double计算精度问题
java中的float.double计算存在精度问题,这不仅仅在java会出现,在其他语言中也会存在,其原因是出在IEEE 754标准上. 而java对此提供了一个用于浮点型计算的类——BigDeci ...
- 【转】JAVA程序中Float和Double精度丢失问题
原文网址:http://blog.sina.com.cn/s/blog_827d041701017ctm.html 问题提出:12.0f-11.9f=0.10000038,"减不尽" ...
- 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 ...
- Effective Java 67 Avoid excessive synchronization
Principle To avoid liveness and safety failures, never cede control to the client within a synchroni ...
- java 小心使用float和double他可能不如你所想
public static void main(String[] args) { double funds=1.00; ; // ; ;funds>=price;price+=.){ funds ...
- Effective Java 07 Avoid finallizers
NOTE Never do anything time-critical in a finalizer. Never depend on a finalizer to update critical ...
- Effective Java 73 Avoid thread groups
Thread groups were originally envisioned as a mechanism for isolating applets for security purposes. ...
- Effective Java 05 Avoid creating unnecessary objects
String s = new String("stringette"); // Don't do this. This will create an object each tim ...
随机推荐
- SQL查询语句去除重复行
1.存在两条完全相同的纪录 这是最简单的一种情况,用关键字distinct就可以去掉 select distinct * from table(表名) where (条件) 2.存在部分字段相同的纪录 ...
- Angular系列----AngularJS入门教程01:AngularJS模板 (转载)
是时候给这些网页来点动态特性了——用AngularJS!我们这里为后面要加入的控制器添加了一个测试. 一个应用的代码架构有很多种.对于AngularJS应用,我们鼓励使用模型-视图-控制器(MVC)模 ...
- Linux永久修改系统时间和时区方法
修改时区: 1> 找到相应的时区文件 /usr/share/zoneinfo/Asia/Shanghai 用这个文件替换当前的/etc/localtime文件. 或者找你认为是标准时间的服务器, ...
- Github教程(1)
Git基本命令 git diff:查看工作树,暂存区,最新提交之间的差别 举例: 在README.MD中增加一行 ## This is the subtitle 执行git diff 命令,查看当前工 ...
- ADO.NET常用对象的基础概念强化
1.Command对象 1.1 ExcuteNonquery---执行非查询语句,返回受影响的行数,在新增,删除,修改的时候,如果我们要返回结果集那么就不能使用它了: 1.2 ExcuteScalar ...
- Orleans之Hello World
接触Orleans 有一段时间了,之前也翻译了一系列官网文档,今天我们就来一个实际的例子,来看看到底如何用这个东西来开发项目,当然经典的也是醉人的,我们就从HelloWorld开始吧. 通过前面的知识 ...
- (二)Protobuf的C#使用
[转]http://blog.csdn.net/shantsc/article/details/50729402 protobuf c#版本分成两个版本,一个是protobuf-net,另一个是pr ...
- 将HTML5 Canvas的内容保存为图片
主要思想是借助Canvas自己的API - toDataURL()来实现,整个实现 HTML + JavaScript的代码很简单. 代码如下: <html> <meta http- ...
- OAuth2.0 基础概述
web:http://oauth.net/2/ rfc:http://tools.ietf.org/html/rfc6749 doc:http://oauth.net/documentation/ c ...
- jquery fadeOut 异步
1. 概述 jquery实现动画效果的函数使用起来很方便,不过动画执行是异步的, 所以要把自定义的操作放在回调函数里. 2. example <html> <body> < ...