0

Am using following function:

def round_half_away_from_zero(n, decimals=1):
    rounded_abs = round_half_up(abs(n), decimals)
    return math.copysign(rounded_abs, n)   

def round_half_up(n, decimals=1):
    multiplier = 10 ** decimals
    return math.floor(n*multiplier + 0.5) / multiplier

def round_half_down(n, decimals=1):
    multiplier = 10 ** decimals
    return math.ceil(n*multiplier - 0.5) / multiplier

df['temp'] = df3['temp'].apply(lambda x: round_half_away_from_zero(x))

he float then updates and the whole column except three entries act like the supposed to: for example:

  • 63.5 = 63.5
  • 58.355 = 58.4
  • 88.878 = 88.9
  • 48.75 = 48.8

Strangely enough, only three entries dont work and they are:

  • 67.75 = 67.7
  • 58.25 = 58.2
  • 46.65 = 46.6

If i just do the function on the single value it works, but not in the series, for example:

round_half_away_from_zero(67.5) ,

it works and gives 67.8, 58.3 and 46.7 respectively.

Any ideas, Thanks

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Jienkles
  • 133
  • 9

2 Answers2

0

Your code works - cannot replicate your error:

import pandas as pd
import math
def round_half_away_from_zero(n, decimals=1):
    rounded_abs = round_half_up(abs(n), decimals)
    return math.copysign(rounded_abs, n)   

def round_half_up(n, decimals=1):
    multiplier = 10 ** decimals
    return math.floor(n*multiplier + 0.5) / multiplier
df = pd.DataFrame( {"A": [63.5, 58.355, 88.878, 48.75] , 
                    "B": [67.75, 58.25, 46.65, 67.75] })


df['A_ok'] = df['A'].apply(lambda x: round_half_away_from_zero(x))
df['B_ok'] = df['B'].apply(lambda x: round_half_away_from_zero(x))

print(df)

Output:

# python 2.7
        A      B  A_ok  B_ok
0  63.500  67.75  63.5  67.8
1  58.355  58.25  58.4  58.3
2  88.878  46.65  88.9  46.7
3  48.750  67.75  48.8  67.8

# python 3.6
        A      B  A_ok  B_ok
0  63.500  67.75  63.5  67.8
1  58.355  58.25  58.4  58.3
2  88.878  46.65  88.9  46.7
3  48.750  67.75  48.8  67.8
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

Hi back to this question, i found out that the three numbers i have problems with when multiply the decimals by 100, it rounded down - this was a floating point problem and i solved it by converting to decimal package before rounding off

Jienkles
  • 133
  • 9