19

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);
mhasan
  • 3,595
  • 1
  • 17
  • 35
Cmi
  • 409
  • 2
  • 4
  • 12
  • Duplicate/similar: https://stackoverflow.com/questions/9303604/rounding-up-a-number-to-nearest-multiple-of-5 – Mr-IDE Sep 04 '18 at 18:43

2 Answers2

35

You can use Math.round(num/10.0) * 10.

Zarwan
  • 5,167
  • 4
  • 28
  • 46
23
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

Community
  • 1
  • 1
sinsuren
  • 1,745
  • 2
  • 20
  • 25