[英]Sending different json requests but getting similar results in Python
[英]Rounding two similar numbers and getting different results Python
我正在嘗試比較 Python 中的兩個不同值: 59.725和59.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.73和59.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.