Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 479
  • Last Modified:

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.
0
edvinson
Asked:
edvinson
  • 4
  • 2
  • 2
  • +1
1 Solution
 
ozoCommented:
(x + 4) / 5 * 5
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
int num = 123;

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

Open in new window

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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now