gpt4 book ai didi

java - 为什么 BigDecimal 构造函数实例具有不同的值?

转载 作者:行者123 更新时间:2023-11-30 08:04:44 28 4
gpt4 key购买 nike

我不知道为什么会发生这种情况:

float flo = 196.7f;
BigDecimal bd = new BigDecimal(flo);
System.out.println(bd); //print 196.6999969482421875

BigDecimal bd2 = new BigDecimal(Float.toString(flo));
System.out.println(bd2); //print 196.7

最佳答案

您的两个问题在 Javadoc 中都有明确说明。

  1. The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
  2. The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

关于java - 为什么 BigDecimal 构造函数实例具有不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31296388/

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