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 ...
随机推荐
- 利用 ELK系统分析Nginx日志并对数据进行可视化展示
一.写在前面 结合之前写的一篇文章:Centos7 之安装Logstash ELK stack 日志管理系统,上篇文章主要讲了监控软件的作用以及部署方法.而这篇文章介绍的是单独监控nginx 日志分析 ...
- KeyValue Config
public class ConfigHelper { public static ScriptsHelper Scripts { get { return new ScriptsHelper(); ...
- TreeSet与TreeMap浅解
TreeSet与TreeMap的关系: 1.TreeSet 实际上就是用TreeMap来组织数据的,因为在TreeSet中保存了一个NavigableMap<e,Object>接口实例变量 ...
- IE11之F12 Developer Tools--调试器(Debugger)
使用调试器工具在代码运行时对其导航.设置监视点和断点,查看调用堆栈,以及提高编译/精简JavaScript的可读性. 调试器可以帮助你了解为何你的代码片段会出现未按照预期方式运行.未在预期时间运行及在 ...
- [C/C++][文件操作] 对比目录并列出同名较新文件、较旧文件 0.1
主要是模仿robocopy的部分功能 (robocopy /L 参数可以列出本地目录和备份目录中的异同之处,主要是标记出:较新的.较旧的.多出的文件 ) 现在还不会写GUI,打算后面自己做目录树dif ...
- Linq专题之Lambda表达式
这一节我们讲的Lambda表达式跟匿名函数有关.Lambda表达式就是一个匿名函数,它可以包含表达式和语句,并且可以创建委托和表达式树. Lambda表达式的组成: 输入参数.Lambda运算符(=& ...
- Unity实现滑页效果(UGUI)
简介 项目需要...直接展示效果吧: 原理 使用UGUI提供的ScrollRect和ScrollBar组件实现基本滑动以及自己控制每次移动一页来达到滑页的效果. 实现过程 1.创建两个panel,上面 ...
- Unity烂笔头1-自定义INSPECTOR属性窗口节点项
1.添加输入框和标签 LevelScript: using UnityEngine; using System.Collections; public class LevelScript : Mono ...
- Aspose.Words.Tables.Row类操作word表格行
http://www.aspose.com/docs/display/wordsnet/Aspose.Words.Tables.Row+Class Retrieves the index of a r ...
- Studio for WPF:定制 C1WPFChart 标记
在本篇文章中,我们将阐述如何定制 C1WPFChart 数据点的标记. 下面分步讲解实现: 1.定制自定义样式: 1: <Window.Resources> 2: <Style x: ...