Reputation: 57
Math.round(4816.5)
is returning 4817.
I want to round up only if decimal is >5 and not >=5. So here, I need result as 4816.
Please give me solutions.
Upvotes: 1
Views: 4283
Reputation: 274522
Use a RoundingMode of HALF_DOWN and let Java take care of the rest:
BigDecimal value = new BigDecimal(4816.5);
value = value.setScale(0, RoundingMode.HALF_DOWN);
long result = value.longValue();
System.out.println(result);
Upvotes: 5
Reputation: 72638
Math.round(n)
is basically the same as (long) Math.floor(n + 0.5)
so you can just modify that algorithm slightly:
long rounded = (long) Math.ceil(n - 0.5);
Upvotes: 6