11

I want to round integers to the nearest 0.25 decimal value, like this:

import math

def x_round(x):
    print math.round(x*4)/4

x_round(11.20) ## == 11.25
x_round(11.12) ## == 11.00
x_round(11.37) ## == 11.50

This gives me the following error in Python:

Invalid syntax
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Thom
  • 197
  • 1
  • 2
  • 7
  • `round` is a built-in function. It is not defined in math. – shanmuga Oct 21 '15 at 11:05
  • Your last example is wrong because 11.37 is nearer 11.25 and not 11.50 – Avihoo Mamka Oct 21 '15 at 11:09
  • 1
    See [here](http://stackoverflow.com/questions/20457038/python-how-do-round-down-to-2-decimals) for the other issue you'll run into once your `print` works. – TigerhawkT3 Oct 21 '15 at 11:10
  • Or see [here](http://stackoverflow.com/questions/4518641/how-to-round-off-a-floating-number-in-python) if you want floor or ceiling results rather than rounding. – TigerhawkT3 Oct 21 '15 at 11:13

2 Answers2

28

The function math.rounddoes not exist, just use the built in round

def x_round(x):
    print(round(x*4)/4)

Note that print is a function in Python 3, so the parentheses are required.

At the moment, your function doesn't return anything. It might be better to return the value from your function, instead of printing it.

def x_round(x):
    return round(x*4)/4

print(x_round(11.20))

If you want to round up, use math.ceil.

def x_round(x):
    return math.ceil(x*4)/4
Alasdair
  • 298,606
  • 55
  • 578
  • 516
12

round is a built-in function in Python 3.4, and print syntax is changed. This works fine in Python 3.4:

def x_round(x):
    print(round(x*4)/4)

x_round(11.20) == 11.25
x_round(11.12) == 11.00
x_round(11.37) == 11.50
Ho1
  • 1,239
  • 1
  • 11
  • 29