Java – why doesn’t my operation work when I use BigDecimal?

I'm trying to operate with BigDecimal, but it always returns 0 Why does double work when I use it?

public static void main(String[] args) {
    double a = 3376.88;
    BigDecimal b = new BigDecimal(a);
    System.out.println(a-a/1.05);
    System.out.println(b.subtract(b).divide(new BigDecimal(1.05)).doubleValue());
}

thank you.

Solution

You did not perform the same operation

When you perform dual operations, the normal Java operation sequence is being applied:

a-a/1.05  
= a - (a/1.05)

However, when you run methods on BigDecimal, the operations are evaluated in the order you call them, so

b.subtract(b).divide(new BigDecimal(1.05))

amount to

(b - b) / 1.05
= 0 / 1.05
= 0
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>