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!

5
  • Post your code. We need to reproduce your problem. Commented Jun 29, 2022 at 13:26
  • 2
    thats not how rounding works Commented Jun 29, 2022 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). Commented Jun 29, 2022 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 Commented Jun 29, 2022 at 13:28
  • As LowIntHighCha suggests: answered Commented Jun 29, 2022 at 13:30

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.