gpt4 book ai didi

java - 关于BigDecimal

转载 作者:行者123 更新时间:2023-12-02 04:18:28 25 4
gpt4 key购买 nike

我为这个双变量执行以下 java print 命令双重测试=58.15;当我执行 System.out.println(test); 时和 System.out.println(new Double(test).toString());它打印为 58.15。

当我执行 System.out.println(new BigDecimal(test)) 时,我得到以下值58.14999999999999857891452847979962825775146484375

我能够理解“测试”双变量值在内部存储为 58.1499999。但是当我执行以下两个 System.out.println 时,我得到的输出为 58.15 而不是 58.1499999。

System.out.println(测试);

System.out.println(new Double(test).toString());

上面两个的输出结果为 58.15。

上面的 System.out.println 语句是否对值 58.1499999 进行了舍入并将其打印为 58.15?

最佳答案

System.out.println(new BigDecimal("58.15"));

要从硬编码常量构造 BigDecimal,必须始终使用类中的常量之一( ZEROONETEN )或字符串构造函数之一。原因是,如果您将值放入 double 型中,您就已经失去了无法恢复的精度。

编辑:polygenelubricants 是对的。具体来说,您正在使用 Double.toString或等效的。引用那里的内容:

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.

关于java - 关于BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2406207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com