26

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,703
  • 1
  • 18
  • 37
Cmi
  • 479
  • 2
  • 5
  • 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

40

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

Zarwan
  • 5,537
  • 4
  • 30
  • 48
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
  • 23
  • 26