Android/Java: Rounding up a number to get no decimal

29,966

Solution 1

And if you're working with only positive numbers, you can also use int i = (int)(d + 0.5).

EDIT: if you want to round negative numbers up (towards positive infinity, such that -5.4 becomes -5, for example), you can use this as well. If you want to round to the higher magnitude (rounding -5.4 to -6), you would be well advised to use some other function put forth by another answer.

Solution 2

With the standard rounding function? Math.round()

There's also Math.floor() and Math.ceil(), depending on what you need.

Solution 3

You can use

int i = Math.round(f); long l = Math.round(d);

where f and d are of type float and double, respectively.

Solution 4

new BigDecimal(3.4);
Integer result = BigDecimal.ROUND_HALF_UP;

Or

Int i = (int)(202.22d);

Solution 5

Java provides a few functions in the Math class to do this. For your case, try Math.ceil(4.5) which will return 5.

Share:
29,966
don
Author by

don

Updated on September 14, 2020

Comments

  • don
    don over 3 years

    How to round up a decimal number to a whole number.

    3.50 => 4

    4.5 => 5

    3.4 => 3

    How do you do this in Java? Thanks!

  • Dmitry
    Dmitry over 5 years
    Math.round() returns long - not int.