I want to round decimal number as follows:-
n = 3.2 result n = 3
n= 3.6 result n= 4
Basically if decimal is between .0 to .4 then it should round down AND if decimal is between .5 to .9 then it should round up.
n = 3.0 result = 3
n = 3.5 result = 3.5
You can use modulus %
or substract -
by int
:
def round_(n):
if (n % int(n) == 0.5):
return n
else:
return round(n)
print (round_(3.6))
4
print (round_(3.5))
3.5
print (round_(3.4))
3
def round_(n):
if (n - int(n) == 0.5):
return n
else:
return round(n)
Try this,
you have to make a custom round function as per your requirements.
def round_(n):
if n-int(n) == 0.5:
return n
else:
return round(n)
Results
In [21]: round_(3.6)
Out[21]: 4.0
In [22]: round_(3.5)
Out[22]: 3.5
In [23]: round_(3.2)
Out[23]: 3.0
As I understand your use case, you should use
def r(x):
return round(x * 2.0) / 2.0
Examples:
r(3.4) -> 3.5
r(3.24) -> 3.0
r(3.25) -> 3.5
r(3.74) -> 3.5
r(3.75) -> 4.0
use
import math
print math.ceil(x) and math.floor(x)
or
def round(x):
if (n % int(x) == 0.5):
return x
else:
return round(n=x)
print (round_(3.8))
4
print (round_(3.5))
3.5
print (round_(3.2))
3
or check this https://stackoverflow.com/a/29308619/6107715
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.