java.lang.Math 类有 ceil()、floor()、round() 方法,但没有 trunc() 方法。
同时,我在实践中看到 .intValue() 方法(实际上执行 (int) 转换)完全符合我对 trunc() 的标准含义的期望。
但是我找不到任何具体文档来确认 intValue() 完全等同于 trunc(),从很多角度来看这都很奇怪,例如:
描述“以 int 形式返回此 Double 的值(通过 转换为 int 类型)” https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html做 不要说它“返回小数的整数部分” 数字”或类似的内容。
文章 What is .intValue() in Java? 没有说任何它的行为类似于 trunc()。
我对“Java trunc method”或类似方法的所有搜索都没有给出 好像我是唯一一个搜索 trunc() 的人并且好像我 不知道一些大家都知道的非常常见的事情。
我能以某种方式确认我可以安全地使用 intValue() 来使用“trunc”模式四舍五入小数吗?
最佳答案
所以问题就变成了:将 double 转换为 int 是否等于截断?
Java Language Specification或许会有答案。我引用一下:
specific conversions on primitive types are called the narrowing primitive conversions:
[...]
- float to byte, short, char, int, or long
- double to byte, short, char, int, long, or float
A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.
[...]
A narrowing conversion of a floating-point number to an integral type T takes two steps:
- In the first step, the floating-point number is converted either to [...] an int, if T is byte, short, char, or int, as follows:
- If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.
- Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:
- If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.
- Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.
IEEE 754-1985 中对此进行了描述.
关于Java trunc() 等效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58220779/