Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading