Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Last active March 13, 2025 19:33
Show Gist options
  • Save hughdbrown/637f806498e4b50a1ed7e4627fa72f25 to your computer and use it in GitHub Desktop.
Save hughdbrown/637f806498e4b50a1ed7e4627fa72f25 to your computer and use it in GitHub Desktop.
Truncating numbers

The problem

So you are interested in rounding a number to its lowest multiple. Let's say you want numbers to be rounded to 10:

>>> for number in range(30):
...     print(f"{number}: {10 * (number // 10)}")
...
0: 0
1: 0
2: 0
3: 0
4: 0
5: 0
6: 0
7: 0
8: 0
9: 0
10: 10
11: 10
12: 10
13: 10
14: 10
15: 10
16: 10
17: 10
18: 10
19: 10
20: 20
21: 20
22: 20
23: 20
24: 20
25: 20
26: 20
27: 20
28: 20
29: 20

An alternative

An aternative is to use a power of two instead of 10 -- say, 8. Then we subtract the number bit-and-ed with a mask (the power of two minus 1 -- 7, in our case):

>>> mask = 8 - 1
... for number in range(30):
...     print(f"{number}: {number - (number & mask)}")
...
0: 0
1: 0
2: 0
3: 0
4: 0
5: 0
6: 0
7: 0
8: 8
9: 8
10: 8
11: 8
12: 8
13: 8
14: 8
15: 8
16: 16
17: 16
18: 16
19: 16
20: 16
21: 16
22: 16
23: 16
24: 24
25: 24
26: 24
27: 24
28: 24
29: 24

The benefit

See how the numbers go up by 8 every 8 numbers? If you choose a power of two, then you get this result at very low computation cost.

@hughdbrown
Copy link
Author

Unfortunately, Scratch does not have bit-operators:

No, Scratch, a visual programming language, does not have built-in bitwise operators (like AND, OR, XOR) for directly manipulating individual bits within numbers. However, you can simulate bitwise operations using arithmetic and conditional logic.

Instead, you can use the mod operator in Scratch:

chunk = 8
truncated = number - (number mod chunk)

This also works for the original value of 50 that you were using:

chunk = 50
truncated = number - (number mod chunk)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment