像Python中的Excel一样截断小数位

问题描述 投票:0回答:1

在我的 Excel 文件中,我有一些计算。计算返回 0,345,Excel 将其转换为 0,35。我用Python做的。 Python 返回 0,345,但我想像 Excel 一样获取 0,35。我尝试过 round() 方法,但它返回 0.34。

python excel floating-point decimal floating-accuracy
1个回答
0
投票

尝试这样

# Your initial number
number = 0.345

# Rounding the number to two decimal places
rounded_number = round(number, 2)

# Format the rounded number to a string with two decimal places
formatted_number = '{:.2f}'.format(rounded_number)

print(formatted_number)  # Output: '0.35'
© www.soinside.com 2019 - 2024. All rights reserved.