How to use decimal for rounding values in Python

10 views

```import decimal

context = decimal.getcontext()

context.rounding = decimal.ROUND_HALF_UP

print(round(decimal.Decimal('3.1'), 0))
print(round(decimal.Decimal('3.4'), 0))
print(round(decimal.Decimal('3.5'), 0))
print(round(decimal.Decimal('3.6'), 0))
print(round(decimal.Decimal('3.9'), 0))

'''
run:

3
3
4
4
4

'''```

edited Jun 9 by avibootz
```import decimal

context = decimal.getcontext()

context.rounding = decimal.ROUND_HALF_DOWN

print(round(decimal.Decimal('3.1'), 0))
print(round(decimal.Decimal('3.4'), 0))
print(round(decimal.Decimal('3.5'), 0))
print(round(decimal.Decimal('3.6'), 0))
print(round(decimal.Decimal('3.9'), 0))

'''
run:

3
3
3
4
4

'''```

edited Jun 9 by avibootz
```import decimal

context = decimal.getcontext()

context.rounding = decimal.ROUND_HALF_EVEN

print(round(decimal.Decimal('3.1'), 0))
print(round(decimal.Decimal('3.4'), 0))
print(round(decimal.Decimal('3.5'), 0))
print(round(decimal.Decimal('3.6'), 0))
print(round(decimal.Decimal('3.9'), 0))

'''
run:

3
3
4
4
4

'''```

```import decimal

context = decimal.getcontext()

context.rounding = decimal.ROUND_CEILING

print(round(decimal.Decimal('3.1'), 0))
print(round(decimal.Decimal('3.4'), 0))
print(round(decimal.Decimal('3.5'), 0))
print(round(decimal.Decimal('3.6'), 0))
print(round(decimal.Decimal('3.9'), 0))

'''
run:

4
4
4
4
4

'''```

```import decimal

context = decimal.getcontext()

context.rounding = decimal.ROUND_DOWN

print(round(decimal.Decimal('3.1'), 0))
print(round(decimal.Decimal('3.4'), 0))
print(round(decimal.Decimal('3.5'), 0))
print(round(decimal.Decimal('3.6'), 0))
print(round(decimal.Decimal('3.9'), 0))

'''
run:

3
3
3
3
3

'''```

```import decimal

context = decimal.getcontext()

context.rounding = decimal.ROUND_FLOOR

print(round(decimal.Decimal('3.1'), 0))
print(round(decimal.Decimal('3.4'), 0))
print(round(decimal.Decimal('3.5'), 0))
print(round(decimal.Decimal('3.6'), 0))
print(round(decimal.Decimal('3.9'), 0))

'''
run:

3
3
3
3
3

'''```

```import decimal

context = decimal.getcontext()

context.rounding = decimal.ROUND_UP

print(round(decimal.Decimal('3.1'), 0))
print(round(decimal.Decimal('3.4'), 0))
print(round(decimal.Decimal('3.5'), 0))
print(round(decimal.Decimal('3.6'), 0))
print(round(decimal.Decimal('3.9'), 0))

'''
run:

4
4
4
4
4

'''```