Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python round to nearest 0.25 [duplicate]

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
like image 224
Thom Avatar asked Oct 21 '15 11:10

Thom


1 Answers

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
like image 68
Alasdair Avatar answered Sep 30 '22 01:09

Alasdair