ajnabz
ajnabz

Reputation: 308

Rounding two similar numbers and getting different results Python

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!

Upvotes: 0

Views: 106

Answers (2)

bekirbakar
bekirbakar

Reputation: 166

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

Upvotes: 2

Terminologist
Terminologist

Reputation: 993

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)

Upvotes: 1

Related Questions