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
  • 317
  • 1
  • 10
Piyush S. Wanare
  • 4,703
  • 6
  • 37
  • 54

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
  • 822,522
  • 95
  • 1,334
  • 1,252
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
  • 15,740
  • 4
  • 35
  • 52
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
  • 16,716
  • 11
  • 50
  • 65
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
  • 6,458
  • 9
  • 31
  • 58