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

7

10

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!

Sightless answered 9/7, 2012 at 14:5 Comment(0)
B
9

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.

Banal answered 9/7, 2012 at 14:21 Comment(0)
L
27

With the standard rounding function? Math.round()

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

Lochia answered 9/7, 2012 at 14:7 Comment(0)
V
13

You can use

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

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

Vally answered 9/7, 2012 at 14:8 Comment(1)
Math.round() returns long - not int.Lail
B
9

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.

Banal answered 9/7, 2012 at 14:21 Comment(0)
J
2

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

Jamal answered 9/7, 2012 at 14:7 Comment(0)
S
2
new BigDecimal(3.4);
Integer result = BigDecimal.ROUND_HALF_UP;

Or

Int i = (int)(202.22d);
Sightless answered 9/7, 2012 at 15:39 Comment(0)
T
1

Using Math.max you can do it like this:

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

This would give you 2

Totemism answered 10/7, 2017 at 16:38 Comment(0)
A
0

Use Math.round() method rounds a number to the nearest integer. Examples : 2.49 will be rounded down 2 2.5 will be rounded up 3

Autoplasty answered 22/2, 2024 at 12:25 Comment(2)
You provided an answer for the question of "how to round to the closest number", whereas the actual question was "how to round a number to its higher bound if it's not an integer"Vicissitude
Pardon me, but I don't see how your answer provides anything that does not already appear in the other answers.Lunneta

© 2022 - 2025 — McMap. All rights reserved.