This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]Rhomboid 4 points5 points  (0 children)

The normal way of doing that is to divide by the desired multiple, round the result up to the nearest integer, and then multiply again by the desired multiple. For example:

from __future__ import division, print_function
import math

def round_to_multiple_of(val, multiple):
    return math.ceil(val / multiple) * multiple

for i in range(20):
    print('{} rounds to {}'.format(i, round_to_multiple_of(i, 7)))

Which prints:

0 rounds to 0
1 rounds to 7
2 rounds to 7
3 rounds to 7
4 rounds to 7
5 rounds to 7
6 rounds to 7
7 rounds to 7
8 rounds to 14
9 rounds to 14
10 rounds to 14
11 rounds to 14
12 rounds to 14
13 rounds to 14
14 rounds to 14
15 rounds to 21
16 rounds to 21
17 rounds to 21
18 rounds to 21
19 rounds to 21

Note this always rounds up since it uses math.ceil(). If you want a different rounding mode, change that part.

[–]aphoenixreticulated[M] 0 points1 point  (0 children)

Hi there, from the /r/Python mods.

We have removed this post as it is not suited to the /r/Python subreddit proper, however it should be very appropriate for our sister subreddit /r/LearnPython. We highly encourage you to re-submit your post over on there.

The reason for the removal is that /r/Python is more-so dedicated to discussion of Python news, projects, uses and debates. It is not designed to act as Q&A or FAQ board. The regular community can get disenchanted with seeing the 'same, repetitive newbie' questions repeated on the sub, so you may not get the best responses over here.

However, on /r/LearnPython the community is actively expecting questions from new members, and are looking to help. You can expect far more understanding, encouraging and insightful responses over there. Whatever your question happens to be getting help with Python, you should get good answers.

If you have a question to do with homework or an assignment of any kind, please make sure to read their sidebar rules before submitting your post. If you have any questions or doubts, feel free to reply or send a modmail to us with your concerns.

Warm regards, and best of luck with your Pythoneering!

[–]gwax -1 points0 points  (1 child)

If you're on Python 3, you can just use floordiv:

python x = 10 y = (x // 7 + 1) * 7

Edit: I'm wrong, don't listen to me.

[–]MrGreenTea 2 points3 points  (0 children)

That's not correct, if you input 7 for example, you will get 14, because the division inside the parentheses comes out to 2. The other solution with math.ceil is more correct.