Math.round() Method in Java
开发者_如何学JAVAMath.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.
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);
Use a double negative:
-Math.round(-n)
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);
精彩评论