0

For my project I have decided to store money as an Integer (pence) instead of using BigDecimal and Co.

But I'm having some trouble with percentage calculation and two decimal rounding.

for example I wish to calculate the 2.9% of 11.88$ which would be:

1188 * 0.029 = 34.452 = 35 (so 0.35$)
(the .4 round to .5 so the 34 round 35)

But cannot manage to arrive to this result using Math.round or Math.ceil.

double r = Math.round(34.452)  
r = 34

is there a way in Java using double/long to round as in my example ?

(Note: using BigDecimal and setScale(2, RoundingMode.CEILING) is works perfectly)

1.03356 1.03356

Johny19
  • 5,364
  • 14
  • 61
  • 99
  • 1
    Why do you want .34452 to "round" to .35? That's not how standard mathematical rounding works; it's _only_ the leftmost truncated digit that matters: .34500 and above rounds to .35, and .34499 and below rounds to .34. Alternatively, _banker's rounding_ is almost identical, except that if the truncated part is 500, you round towards even numbers. – Aasmund Eldhuset Feb 22 '16 at 17:49
  • 1
    *"(the .4 round to .5 so the 34 round 35),"* That is not how rounding works. – clcto Feb 22 '16 at 17:49
  • There is a similar question and a complete answer in: http://stackoverflow.com/questions/7139382/java-rounding-up-to-an-int-using-math-ceil – Jessica Feb 22 '16 at 18:07
  • 1
    @AasmundEldhuset and clcto, thanks. I should have paid more attention in class – Johny19 Feb 22 '16 at 19:36
  • If it's a comfort, I also initially misunderstood rounding when I learned about it and thought that you were supposed to cascade all of the digits :) – Aasmund Eldhuset Feb 22 '16 at 21:45

0 Answers0