Solved

# How to round to nearest 5

Posted on 2013-06-18
466 Views
This is proving more difficult than I expected.

How do I round an integer up to the nearest '5'?

346 = 350

123 = 125

876 = 880

etc.

I tried ceil , but can't get it to produce correct result.

Thank you.
0
Question by:edvinson
• 4
• 2
• 2
• +1

LVL 84

Expert Comment

ID: 39258409
(x + 4) / 5 * 5
0

LVL 35

Accepted Solution

mccarl earned 500 total points
ID: 39258412
``````int num = 123;

num = ((int) ((num + 4) / 5)) * 5;
``````
0

LVL 33

Expert Comment

ID: 39258522
the 'nearest' 5 of 346 is 345 and not 350.

Sara
0

LVL 35

Expert Comment

ID: 39258530
@Sara,

But the question author did say, "How do I round an integer up to the nearest '5'?"

Easily missed though! ;)
0

LVL 84

Expert Comment

ID: 39258568
If you need it to work with both positive and negative ints
x+(-x%5+5)%5
0

LVL 33

Expert Comment

ID: 39258660
yes. i didn't read the 'up'. :-)

Sara
0

LVL 35

Expert Comment

ID: 39259590
@Sara, I have actually just now read the title of the question where the author HASN'T used the word 'up' so yes, that does leave it not 100% clear what the author was after! ;)
0

LVL 1

Author Comment

ID: 39267624
I did mean round up. thank you everyone. it looks so easy once I study your code!
0

LVL 35

Expert Comment

ID: 39267684
Not a problem, glad to help!
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question