floating-point - python - 如何将浮点数四舍五入到特定的小数位数？

`round(8.8333333333333339, 2)`提供`8.83`而且非`8.84` ，我是python新手，也是编程新手。

`8.833333333339` (或 `8.833333333333334``106.00/12`的结果)正确舍入为两位小数，数学上听起来像你想要的ceiling函数，python模块的`math`中的一个名为 `ceil`

```
```
import math

v = 8.8333333333333339

print(math.ceil(v*100)/100) # -> 8.84

``````

```
```
def ceiling(x):

n = int(x)

return n if n-1 <x <= n else n+1

``````

```
```
>>> import decimal

>>> a = decimal.Decimal(" 8.833333333339" )

>>> print(round(a,2))

8.83

``````

```
```
>>> import decimal

>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP)

Decimal('8.34')

>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)

Decimal('8.33')

>>>

``````

```
```
total_price = float()

price_1 = 2.99

price_2 = 0.99

total_price = price_1 + price_2

``````

``` ```
3.9800000000000004

``` ```

```
```
print(round(total_price,2))

``````

``` ```
3.98

``` ```

round()函数通过接受两个参数来工作，第一个是你想要的数字，第二个是四舍五入的小数点数。

```
```
print" %.2f" % 8.833333333339 #(Replace number with the variable?)

``````

```
```
" %.2f" % (math.ceil(x * 100)/100)

``````

```
```
def roundno(no):

return int(no//1 + ((no%1)/0.5)//1)

``````

``` ```
format()

``` ```

```
```
format(1.242563," .2f" )

``````

``` ```
1.24

``` ```

```
```
format(9.165654," .1f" )

``````

``` ```
9.2

``` ```

<. 5向下舍入

=. 5四舍五入

```
```
import math

def _should_round_down(val: float):

if val <0:

return ((val * -1) % 1) <0.5

return (val % 1) <0.5

def _round(val: float, ndigits=0):

if ndigits> 0:

val *= 10 ** (ndigits - 1)

is_positive = val> 0

tmp_val = val

if not is_positive:

tmp_val *= -1

rounded_value = math.floor(tmp_val) if _should_round_down(val) else math.ceil(tmp_val)

if not is_positive:

rounded_value *= -1

if ndigits> 0:

rounded_value/= 10 ** (ndigits - 1)

return rounded_value

# test

# nr = 12.2548

# for digit in range(0, 4):

# print(" {} decimals : {} -> {}" .format(digit, nr, _round(nr, digit)))

# output

# 0 decimals : 12.2548 -> 12

# 1 decimals : 12.2548 -> 12.0

# 2 decimals : 12.2548 -> 12.3

# 3 decimals : 12.2548 -> 12.25

``````