Java trunc() 等效方法

标签 java math rounding

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/

相关文章:

java - 使用路标签署 HTTP 消息时获取 401

java - 关于移位运算符

math - float 学有问题吗?

c++ - 舍入整数例程

javascript - 如何在刻度值中创建具有可变刻度间隔且刻度值之间具有相同距离的左轴

c# - C# 中的小数舍入问题

java - JMeter测试前执行带有spring依赖的java代码

matlab - 使用自定义阈值舍入数字

mysql - 将 SQL 的结果截断为整数值

java - JNA-映射 Delphi 函数