gpt4 book ai didi

Java BigDecimal 区别

转载 作者:行者123 更新时间:2023-12-03 20:18:55 27 4
gpt4 key购买 nike

我想看看是否有人可以解释为什么以下代码适用于 valueOf 但不适用于其他代码。

import java.math.BigDecimal; 
public class Change {
public static void main(String args[]) {
double a = 4.00d;
double b = 3.10d;
BigDecimal a1 = new BigDecimal(a);
BigDecimal b1 = new BigDecimal(b);
BigDecimal diff = a1.subtract(b1);
System.out.println("Double difference");
System.out.println(diff);

float c = 4.00f;
float d = 3.10f;
BigDecimal a2 = new BigDecimal(c);
BigDecimal b2 = new BigDecimal(d);
BigDecimal diff2 = a2.subtract(b2);
System.out.println("Float difference");
System.out.println(diff2);

System.out.println("Valueof Difference");
System.out.println(BigDecimal.valueOf(4.00).subtract(BigDecimal.valueOf(3.10)));

}
}

输出如下:

>java Change
Double difference
0.899999999999999911182158029987476766109466552734375
Float difference
0.900000095367431640625
Valueof Difference
0.9

我的问题是:valueOf() 做了什么来获得精度?有没有其他方法可以在不手动四舍五入到 2 位数的情况下获得正确的结果?

谢谢,

最佳答案

查看 BigDecimal 的源代码,它确实:

public static BigDecimal valueOf(double val) {
// Reminder: a zero double returns '0.0', so we cannot fastpath
// to use the constant ZERO. This might be important enough to
// justify a factory approach, a cache, or a few private
// constants, later.
return new BigDecimal(Double.toString(val));
}

来自其 JavaDoc:

Translates a double into a BigDecimal, using the double's canonical string representation provided by the Double.toString(double) method.

Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double).

由于浮点表示法,double 值与您设置的不完全相同。但是,在 String 表示期间,它会四舍五入它显示的内容。 (所有规则都在 JavaDoc 上)。

此外,由于这种舍入,如果您这样做:

BigDecimal d = BigDecimal.valueOf(4.00000000000000000000000000000000001));

你会得到错误的值。 (d == 4.0)

所以,用字符串初始化它们总是更好。

关于Java BigDecimal 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6021369/

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