0

I am trying to compare two different values in Python: 59.725 and 59.72497.

I am rounding them both using the Python round function as doing df.round(2) doesn't work how I need it to:

def round_df_columns(df, col_list):
        for col_name in col_list:
            for x in df[col_name]:
                rounded_x = round(x, 2)
                df[col_name] = df[col_name].replace(x, rounded_x)
        return df

However, when I do this I get 59.73 and 59.72. Is there a way of rounding these values so that they both round up to 59.73? I couldn't find a similar question, but sorry if this is a duplicate. Thanks!

ajnabz
  • 297
  • 5
  • 25
  • Post your code. We need to reproduce your problem. – nicomp Jun 29 '22 at 13:26
  • 2
    thats not how rounding works – XxJames07- Jun 29 '22 at 13:27
  • That's...correct rounding by Python? Below 5 and round down, 5 and above round up. If you're desperate to round *everything* up, you could just `round(x+0.005, 2)`. – Pam Jun 29 '22 at 13:27
  • You could multiply both numbers by 100, use the ceiling function (math.ceil), and then divide them by 100 again. But the behaviour you've seen from the rounding is mathematically correct - 59.72497 is less than 59.725 (i.e. less than halfway to 59.73) so should round to 59.72 – LowIntHighCha Jun 29 '22 at 13:28
  • As LowIntHighCha suggests: [answered](https://stackoverflow.com/a/9232310/7891382) – IamFr0ssT Jun 29 '22 at 13:30

2 Answers2

2

Simple solution is using math.ceil.

Try

import math

x = math.ceil(100 * 59.72497) / 100
print(x)

y = math.ceil(100 * 59.725) / 100
print(y)

Ouput

59.73
59.73
bekirbakar
  • 166
  • 2
  • 7
1

If you want them to always round up, add 0.005 to the value before you round. E.g.

rounded_x = round(x + 0.005, 2)
Thickycat
  • 894
  • 6
  • 12