How can I round a number to the nearest ten with no if statements? For example, 98 to 100.
int num = 87;
double t;
double d = 1.0 * num; // d = 87.0
t = d/100;
System.out.println(t);
Here's the general rule for rounding: If the number you are rounding is followed by 5, 6, 7, 8, or 9, round the number up. Example: 38 rounded to the nearest ten is 40. If the number you are rounding is followed by 0, 1, 2, 3, or 4, round the number down.
To the nearest ten: 1548 rounds to 1550.
You can use Math.round(num/10.0) * 10
.
answer = ((num+5)/10)*10; // if num is int
where num
is int
and to have more idea, read this quesiton. How to round a number to n decimal places in Java.
Edit:
if num
is double
add typecasting to expression (long)((num+5)/10)
as suggested by @PeterLawrey
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With