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!
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!
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.
With the standard rounding function? Math.round()
There's also Math.floor()
and Math.ceil()
, depending on what you need.
You can use
int i = Math.round(f);
long l = Math.round(d);
where f
and d
are of type float
and double
, respectively.
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.
Java provides a few functions in the Math class to do this. For your case, try Math.ceil(4.5)
which will return 5.
new BigDecimal(3.4);
Integer result = BigDecimal.ROUND_HALF_UP;
Or
Int i = (int)(202.22d);
Using Math.max you can do it like this:
(int) Math.max(1, (long) Math.ceil((double) (34) / 25)
This would give you 2
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
© 2022 - 2025 — McMap. All rights reserved.
Math.round()
returnslong
- notint
. – Lail