java - 如何在 Java 中将 double 轮次显式转换为 int 轮次?

标签 java casting

System.out.println((int)(99.9999999999999));

返回 99

System.out.println((int)(99.999999999999999999999999999999999999999));

返回 100

你能解释一下为什么吗?

最佳答案

double 文字 99.9999999999999 可以表示为小于 100double,因此强制转换to int 截断小数部分,99 是结果。

double 字面值 99.99999999999999999999999999999999999999 具有最接近 100 的实际值,转换为 int 很简单 100 这里。

System.out.println(99.9999999999999);
System.out.println((int)(99.9999999999999));
System.out.println(99.9999999999999 == 100.0);

System.out.println(99.999999999999999999999999999999999999999);
System.out.println((int)(99.999999999999999999999999999999999999999));
System.out.println(99.999999999999999999999999999999999999999 == 100.0);

我在这里使用 100.0 作为 double 文字,比较 2 个 double 值以查看它们是否完全相同 double 值。

打印出来:

99.9999999999999
99
false
100.0
100
true

JLS, Section 3.10.2涵盖浮点文字:

The details of proper input conversion from a Unicode string representation of a floating-point number to the internal IEEE 754 binary floating-point representation are described for the methods valueOf of class Float and class Double of the package java.lang.

Double.valueOf javadocs状态:

Otherwise, s is regarded as representing an exact decimal value in the usual "computerized scientific notation" or as an exact hexadecimal value; this exact numerical value is then conceptually converted to an "infinitely precise" binary value that is then rounded to type double by the usual round-to-nearest rule of IEEE 754 floating-point arithmetic, which includes preserving the sign of a zero value.

(强调我的)

也就是说,该值被四舍五入以产生实际的 double 值。

关于java - 如何在 Java 中将 double 轮次显式转换为 int 轮次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23227191/

相关文章:

java - 在 Java 项目 View 中折叠来自 NetBeans 或 Eclipse 的子包

typescript 错误地将元组推断为数组

java - 无法从 List<List> 转换为 List<List<?>>

java - 我的 App Engine 前端实例使用情况如何?

java - 有没有什么方法可以从文件中扣除内容类型

javascript - 根据 URL 参数更新 html 复选框,而不使用 JavaScript(带有 XSL/XML 的 Java)

c - "Makes Pointer from Integer without a Cast"- 如何满足 GCC?

java - 无法使用 Filters.sharedWithMe() 通过 Google Drive Api 获取与我共享的文件

ios - 如何检查字典值是字符串还是数组

sql - 在 MySQL 中类型转换