Stefano Vercellino
Stefano Vercellino

Reputation: 353

BigDecimal Rounding incorrectly

I was expecting this code:

    double valore = 20.775;

    BigDecimal c = new BigDecimal(valore);
    c = c.setScale(2, RoundingMode.HALF_UP);


    System.out.println(c.doubleValue());

to return 20.78, but it's returning 20.77 instead.

Is it an error? Or am I missing something?

Upvotes: 2

Views: 308

Answers (1)

krossovochkin
krossovochkin

Reputation: 12122

Everything is correct.
You can read some high-level details in another answer on SO or read more in documentation to BigDecimal

It is not common to use BigDecimal constructor with double param, because it will exactly represent what is inside double. So when you write: new BigDecimal(20.775) you are not necessarily have 20.775 as a result (rather you will have something like 20.77499999999999857891452847979962825775146484375)

For you to test:
1) testing BigDecimal representation
a) System.out.println(new BigDecimal(20.775)); => 20.77499999999999857891452847979962825775146484375
b) System.out.println(new BigDecimal("20.775")); => 20.775

2) test rounding with different BigDecimal constructors:
a) new BigDecimal(20.775) after rounding half up will show 20.77.
b) new BigDecimal("20.775") after rounding half up will show 20.78.
c) new BigDecimal(String.valueOf(20.775) after rounding half up will show 20.78.

So as a conclusion: Do not use BigDecimal constructor with double param. Instead use BigDecimal constructor with String param.

Hope it helps

Upvotes: 7

Related Questions