簡體   English   中英

四舍五入兩個相似的數字並得到不同的結果Python

[英]Rounding two similar numbers and getting different results Python

我正在嘗試比較 Python 中的兩個不同值: 59.72559.72497

我正在使用 Python round 函數對它們進行四舍五入,因為df.round(2)無法滿足我的需要:

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

但是,當我這樣做時,我得到59.7359.72 有沒有辦法四舍五入這些值,使它們都四舍五入到 59.73? 我找不到類似的問題,但如果這是重復的,我很抱歉。 謝謝!

簡單的解決方案是使用math.ceil

嘗試

import math

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

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

輸出

59.73
59.73

如果您希望它們總是四舍五入,請在四舍五入之前將值添加 0.005。 例如

rounded_x = round(x + 0.005, 2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM