java - Java 中使用 double 保持精度

标签 java floating-point double precision

public class doublePrecision {
    public static void main(String[] args) {

        double total = 0;
        total += 5.6;
        total += 5.8;
        System.out.println(total);
    }
}

上面的代码打印:

11.399999999999

我怎样才能让它打印(或能够用作)11.4?

最佳答案

正如其他人提到的,您可能想要使用 BigDecimal类,如果您想要 11.4 的精确表示。

现在,稍微解释一下为什么会发生这种情况:

Java 中的 floatdouble 基本类型为 floating point数字,其中数字存储为分数和指数的二进制表示形式。

更具体地说, double 浮点值(例如 double 类型)是 64 位值,其中:

  • 1 位表示符号(正或负)。
  • 11 位指数。
  • 有效数字为 52 位(二进制的小数部分)。

这些部分组合起来生成一个值的double表示。

(来源:Wikipedia: Double precision)

有关 Java 中如何处理浮点值的详细说明,请参阅 Section 4.2.3: Floating-Point Types, Formats, and Values Java 语言规范。

bytecharintlong 类型为 fixed-point数字,是数字的精确表示。与定点数不同, float 有时(可以安全地假设“大多数时间”)无法返回数字的精确表示。这就是为什么 5.6 + 5.8 的结果是 11.399999999999

当需要一个精确的值(例如 1.5 或 150.1005)时,您需要使用一种能够精确表示数字的定点类型。

正如已经多次提到的,Java 有一个 BigDecimal类将处理非常大的数字和非常小的数字。

来自 BigDecimal 类的 Java API 引用:

Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10^-scale).

Stack Overflow 上有很多与 float 及其精度相关的问题。以下是您可能感兴趣的相关问题列表:

如果您确实想了解 float 的具体细节,请查看 What Every Computer Scientist Should Know About Floating-Point Arithmetic .

关于java - Java 中使用 double 保持精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33517156/

相关文章:

java - Mule - 访问异常堆栈并记录特定部分

java - 带有返回数组的参数的类方法

C++ 浮点陷阱

java - 将字符串转换为 double - JAVA

双重自由或腐败的代码

Java:将(长)对象转换为 double 的多种方法

Java.nio : most concise recursive directory delete

java - java中的全局变量

c# - 在 C# 中格式化 double 输出

c - sscanf 使用 c 进行 float