Search code examples
pythonpython-3.xrounding

How would I round a number to a grid using python?


I would like to know how to round numbers to a grid using python. Here is pseudo-code to demonstrate:

GRID_SIZE = 20

def snap_function():
    # snap here
    pass

snapped_number = snap_function(68)
print(snapped_number)
# result is 60

I don't know if I gave enough, thanks!


Solution

  • def snap_function(x,grid_size):
         # x//y will give you the modulo 
         return (x//grid_size) * grid_size
    
    print(snap_function(68,20))
    

    output: 60