深度阅读

How to Round Numbers in Python?

作者
作者
2023年08月22日
更新时间
9.8 分钟
阅读时间
0
阅读量

To round a number in Python, you can use the built-in round() function. The round() function rounds a floating-point number to the nearest integer, or to a specified number of digits after the decimal point. Here are some examples:

To round a number to the nearest integer:

x = 3.14159
rounded = round(x)
print(rounded)  # Output: 3

To round a number to a specified number of decimal places:

x = 3.14159
rounded = round(x, 2)
print(rounded)  # Output: 3.14

In this example, the second argument of round() specifies the number of decimal places to round to.

Note that the default rounding mode used by the round() function is “round half to even,” also known as “banker’s rounding.” This means that if the number to be rounded ends in .5, it will be rounded to the closest even integer. If you want to use a different rounding mode, such as always rounding up or always rounding down, you can use the decimal module or the math module to achieve that.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。