Files
Python_CookBook_repo/3.数字日期和时间/1.对数值进行取整.py
2025-09-10 16:12:45 +08:00

16 lines
692 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == '__main__':
# 很多时候我们需要对浮点数进行取整操作通常情况下使用自带的round函数就能解决问题
f = 1.23456
print(round(f, 2))
# 虽然round函数可以很方便的对数值进行取整但一般情况下如果需要规范输出还是用format(.2f)来做
ff2 = format(f, '.2f')
print(ff2)
# 因为浮点数计算因为算法的局限性可能带来一些奇妙的误差
a = 2.1
b = 4.2
print(a+b)
# 所以一般来说我们就是算完直接按照需要取小数位数规整完格式就行了
# 除非我们的程序对数据精度要求非常高那这时候就要用decimal库了