Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round to the nearest ten? [duplicate]

Tags:

java

rounding

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);
like image 273
Cmi Avatar asked Oct 03 '16 05:10

Cmi


People also ask

How do you round a number to the nearest 10?

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.

What's 1548 rounded to the nearest ten?

To the nearest ten: 1548 rounds to 1550.


2 Answers

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

like image 123
Zarwan Avatar answered Oct 22 '22 20:10

Zarwan


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

like image 45
sinsuren Avatar answered Oct 22 '22 20:10

sinsuren