0

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
Ashan
  • 307
  • 1
  • 10
Piyush S. Wanare
  • 4,179
  • 4
  • 34
  • 50

4 Answers4

2

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)
jezrael
  • 729,927
  • 78
  • 1,141
  • 1,090
1

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
Rahul K P
  • 10,793
  • 3
  • 32
  • 47
1

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
clemens
  • 15,334
  • 11
  • 41
  • 58
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

Community
  • 1
  • 1
Shivkumar kondi
  • 5,968
  • 8
  • 29
  • 55