Java Double value = 0.01 changes to 0.009999999999999787(Java Double 值 = 0.01 更改为 0.009999999999999787)
问题描述
可能重复:
为什么不使用 Double 或 Float 来表示货币?
我正在为我的高中课程用 Java 编写一个基本的命令行程序.我们现在只使用变量.它用于计算购买后您找零中任何类型的纸币和硬币的数量.这是我的程序:
I'm writing a basic command-line program in Java for my high school course. We're only working with variables right now. It's used to calculate the amount of bills and coins of whatever type in your change after a purchase. This is my program:
class Assign2c {
public static void main(String[] args) {
double cost = 10.990;
int paid = 20;
double change = paid - cost;
int five, toonie, loonies, quarter, dime, nickel, penny;
five = (int)(change / 5.0);
change -= five * 5.0;
toonie = (int)(change / 2.0);
change -= toonie * 2.0;
loonies = (int)change;
change -= loonies;
quarter = (int)(change / 0.25);
change -= quarter * 0.25;
dime = (int)(change / 0.1);
change -= dime * 0.1;
nickel = (int)(change / 0.05);
change -= nickel * 0.05;
penny = (int)(change * 100);
change -= penny * 0.01;
System.out.println("$5 :" + five);
System.out.println("$2 :" + toonie);
System.out.println("$1 :" + loonies);
System.out.println("$0.25:" + quarter);
System.out.println("$0.10:" + dime);
System.out.println("$0.05:" + nickel);
System.out.println("$0.01:" + penny);
}
}
它应该一切正常,但在最后一步,当剩下 0.01 美元时,便士的数量应该是 1,但实际上是 0.在进入代码并将更改值输出到控制台几分钟后,我已经发现在最后一步当change = 0.01时,它变为0.009999999999999787.为什么会这样?
It should all work but at the last step when there's $0.01 leftover, number of pennies should be 1 but instead, it's 0. After a few minutes of stepping into the code and outputting the change value to the console, I've found out that at the last step when change = 0.01, it changes to 0.009999999999999787. Why is this happening?
推荐答案
使用 double
作为货币是个坏主意,为什么不使用 Double 或 Float 来表示货币?.我建议使用 BigDecimal
或以美分计算.
Using double
for currency is a bad idea, Why not use Double or Float to represent currency?. I recommend using BigDecimal
or doing every calculation in cents.
这篇关于Java Double 值 = 0.01 更改为 0.009999999999999787的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Double 值 = 0.01 更改为 0.009999999999999787


- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01