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?

Improve company productivity with a Business Account.Sign Up

x
 
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
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.