user462475
user462475

Reputation: 57

Math.round() Method in Java

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

Answers (3)

dogbane
dogbane

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

socket puppet
socket puppet

Reputation: 3219

Use a double negative:

-Math.round(-n)

Upvotes: 5

Dean Harding
Dean Harding

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

Related Questions