Android / Java: rounding a number so that there is no decimal

How to round a decimal number to an integer.

3.50 => 4

4.5 => 5

3.4 => 3

How do you do this in Java? Thanks!

+6
source share
6 answers

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

EDIT: if you want to round negative numbers up (to positive infinity, for example, -5.4 becomes -5, for example), you can also use this. If you want to round to a higher value (rounding from -5.4 to -6), it would be useful for you to use a different function expressed by a different answer.

+6
source

With standard rounding function? Math.round()

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

+20
source

you can use

int i = Math.round(d);

+6
source

Java provides several functions in the Math class for this. For your case, try Math.ceil(4.5) , which will return 5.

+2
source
 new BigDecimal(3.4); Integer result = BigDecimal.ROUND_HALF_UP; 

or

 Int i = (int)(202.22d); 
+2
source

Using Math.max, you can do it like this:

 (int) Math.max(1, (long) Math.ceil((double) (34) / 25) 

It will give you 2

0
source

Source: https://habr.com/ru/post/920041/


All Articles