关于BigDecimal
我为这个双变量执行以下 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
我能够理解“test”双变量值在内部存储为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?
i do the below java print command for this double variable
double test=58.15;
When i do a System.out.println(test); and System.out.println(new Double(test).toString()); It prints as 58.15.
When i do a System.out.println(new BigDecimal(test)) I get the below value
58.14999999999999857891452847979962825775146484375
I am able to understand "test" double variable value is internally stored as 58.1499999. But when i do the below two System.out.println i am getting the output as 58.15 and not 58.1499999.
System.out.println(test);
System.out.println(new Double(test).toString());
It prints the output as 58.15 for the above two.
Is the above System.out.println statements are doing some rounding of the value 58.1499999 and printing it as 58.15?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要从硬编码常量构造 BigDecimal,必须始终使用类中的常量之一 (零, ONE,或 TEN) 或字符串构造函数之一。原因是,如果您将值放入双精度值中,您已经失去了永远无法恢复的精度。
编辑:多基因润滑剂是正确的。具体来说,您正在使用 Double.toString 或同等内容。引用那里的内容:
To construct a BigDecimal from a hard-coded constant, you must always use one of constants in the class (ZERO, ONE, or TEN) or one of the string constructors. The reason is that one you put the value in a double, you've already lost precision that can never be regained.
EDIT: polygenelubricants is right. Specifically, you're using Double.toString or equivalent. To quote from there:
是的,
println
(或更准确地说,Double.toString
)循环。作为证明,System.out.println(.1D);
打印0.1
,这是不可能用二进制表示的。另外,使用 BigDecimal 时,请勿使用 double 构造函数,因为这会尝试精确表示不精确的值。请改用
String
构造函数。Yes,
println
(or more precisely,Double.toString
) rounds. For proof,System.out.println(.1D);
prints0.1
, which is impossible to represent in binary.Also, when using
BigDecimal
, don't use thedouble
constructor, because that would attempt to precisely represent an imprecise value. Use theString
constructor instead.out.println
和Double.toString()
使用 Double.toString(double)。BigDecimal 默认情况下使用更高的精度,如 javadoc,当您调用
toString()
时,它会输出所有字符,最高可达原始双精度数可用的精度级别,因为 .15 没有精确的二进制表示形式。out.println
andDouble.toString()
use the format specified in Double.toString(double).BigDecimal uses more precision by default, as described in the javadoc, and when you call
toString()
it outputs all of the characters up to the precision level available to a primitive double since .15 does not have an exact binary representation.