How to round to nearest 5

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.
LVL 1
edvinsonAsked:
Who is Participating?
 
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
int num = 123;

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

Open in new window

0
 
ozoCommented:
(x + 4) / 5 * 5
0
 
sarabandeCommented:
the 'nearest' 5 of 346 is 345 and not 350.

add 2 to the number (instead of 4) if you agree.

Sara
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
@Sara,

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

Easily missed though! ;)
0
 
ozoCommented:
If you need it to work with both positive and negative ints
x+(-x%5+5)%5
0
 
sarabandeCommented:
yes. i didn't read the 'up'. :-)

Sara
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
@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
 
edvinsonAuthor Commented:
I did mean round up. thank you everyone. it looks so easy once I study your code!
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Not a problem, glad to help!
0
All Courses

From novice to tech pro — start learning today.