Sunday, 18 August 2013

Weird decimal calculation in Java, potentially a bug?

Weird decimal calculation in Java, potentially a bug?

I have weird decimal calculation that really surprise me, I have two big
decimal number, one is a normal proce and the other one is an offer price.
Then I want to calculate discount percentage and ceil it to the nearest
integer.
Here are the code:
BigDecimal listPrice = new BigDecimal(510000);
BigDecimal offerPrice = new BigDecimal(433500);
int itemDiscount = (int)Math.ceil(((listPrice.longValue() -
offerPrice.longValue()) / (float) listPrice.longValue()) * 100);
I expect it would set 15 as value of itemDiscount, but surprisingly it has
16, wow. Then i print each calculation to show in which statement is the
problem, so i put System.out.println for each statement as below :
System.out.println(listPrice.longValue() - offerPrice.longValue()); //==>
show 76500
System.out.println((listPrice.longValue() - offerPrice.longValue()) /
(float) listPrice.longValue()); // ==> 0.15
System.out.println((listPrice.longValue() - offerPrice.longValue()) * 100
/ (float) listPrice.longValue()); // ==> 15.000001
the problem is in above statement, istead of returning 15.0, it return
15.000001. And when i ceil it, it will of course return 16 instead of 15.
What is the explanation if this case? is this the way it is or it is a bug?

No comments:

Post a Comment