java - 为什么浮点值在 sysout 时自动递增

标签 java primitive-types

在我的应用程序中,我使用浮点值来保存客户评分。并且根据要求,分数可以只有5位小数点前和3位小数点后。

例如:99999.999

但是,我不理解使用 sysout 打印浮点值时的奇怪行为。

更多细节请引用下面的示例代码:

public class Test {
    public static void main(String[] args) {
        float f1 = 9999.999f;
        System.out.println(f1);

        float f2 = 99999.999f;
        System.out.println(f2);
    }
}

输出是:

9999.999
100000.0

在这里,为什么值“99999.999”在使用 sysout 时自动增加到“100000.0”? 为什么在点前使用四位十进制数字的值时没有发生同样的事情,即“9999.999”?

任何建议表示赞赏。

最佳答案

来自 java 规范:

float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

总结一下,如果您想节省内存并且不关心精度,请使用 float,否则使用 double。 更多信息在这里 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

我建议使用 BigDecimal 并使用 setScale适合您情况的方法。

关于java - 为什么浮点值在 sysout 时自动递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47119053/

相关文章:

java - 从属性文件中读取值

java - 在java中如果 "char c = ' a' "why does "c = c + 1“无法编译?

c# - 关于字符串是原始类型的分歧

c - 以太网帧中字段的原始 C 类型

java - Oscar OSGi 远程 shell 服务

java - 在移动到下一个之前,您如何完全运行一个 if 语句?

java - 从 C 读取和解释 JVM 内存

kotlin - Kotlin 有原始类型吗?

java - 为什么 NetBeans 会警告将 int[] 传递给 vararg?

java - Eclipse EE 调色板不可用