# Python 四舍五入函数 round

**URL:** <https://www.isharkfly.com/t/python-round/133>\
**Category:** Python\
**Created:** [June 1, 2020, 4:17pm UTC](https://www.isharkfly.com/t/python-round/133 "2020-06-01T16:17:07Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [June 1, 2020, 4:17pm UTC](https://www.isharkfly.com/t/python-round/133/1 "2020-06-01T16:17:07Z")

</div>

小数位的四舍五入在项目中经常用到。

你可能有注意到 round 函数不能真正做到四舍五入。

round() 函数作用就是，返回浮点数x的四舍五入值。

```auto
round( x [, n] )

```

**简单来说就是在浮点运算的时候丢精度。**

这个与计算机系统的设计是有关系的，计算机是使用 2 进制进行计算的的，如果我们常用的数学计算或者科学计算，计算机是会丢精度的。

因此我们的解决方案其实非常简单就是使用 Decimal 来进行数学计算。

浮点计算丢精度的问题不仅仅是 Python 会遇到的问题，Java 、 C/C++ 都会遇到这个问题。

可以考察下面的代码：

```auto
print(round(2.3, 2))
print(round(2.45, 1))
print(round(2.675, 2))

print(Decimal(1.325))

print(Context(prec=3, rounding=ROUND_HALF_UP).create_decimal('2.675'))

```

上面程序的输出为：

```auto
2.3
2.5
2.67
1.3249999999999999555910790149937383830547332763671875
2.68

```

因此，在你需要进行浮点计算的时候，不要使用 Float 进行计算，你需要使用 Decimal 进行数学计算。

 ![Python-float-cal-01](https://com-ossez-www-discourse.s3.dualstack.us-east-2.amazonaws.com/discourse-uploads/original/1X/458f3bf3100617814fa575af71adc7665e7cfb40.jpeg)

例如在 Java 中，我们会使用 BigDecimal 进行精确的科学计算。
