gpt4 book ai didi

python - 格式化方法和舍入数

转载 作者:太空宇宙 更新时间:2023-11-03 15:52:31 24 4
gpt4 key购买 nike

我不明白格式和舍入数字是如何工作的,因为例如:

"{:.0f}".format(234.50) # returns 234
"{:.0f}".format(235.50) # returns 236
"{:.0f}".format(236.50) # returns 236
"{:.0f}".format(237.50) # returns 238

等等……

我错过了什么吗?

感谢您的帮助!

最佳答案

Python 舍入到最接近的整数,但如果小数点是 0.5,它会舍入到最接近的偶数。此方法称为 round half to even并且在许多编程语言中都很常见。

这在 round 的文档中得到确认功能也一样。

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if called with one argument, otherwise of the same type as number.

For a general Python object number, round(number, ndigits) delegates to number.__round__(ndigits).

关于python - 格式化方法和舍入数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45771986/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com