In Python, the round function truncates the decimals by rounding them.
However:
>>> round (3.55, 1) 3.5
The official documentation for the function is interpreted as:
Unfortunately, most decimal fractions cannot is represented exactly as binary fractions. A consequence is so, in general, the decimal floating-point numbers you enter was only approximated by the binary FL Oating-point numbers actually storedin the machine.
>>> Round (0.55, 1) 0.6>>> round (3.55, 1) 3.5
>>> from decimal import decimal>>> decimal (0.55) Decimal (' 0.5500000000000000444089209850062616169452667236328125 ') >>> decimal (3.55) Decimal (' 3.54999999999999982236431605997495353221893310546875 ')
A properly rounded solution is implemented with the decimal module:
from Import *'17.9555'print Context (prec = Len ( Number.split ('. ' 3 round_half_up). Create_decimal (number)
Explanation of the bold part of the code:
- Number is expressed as a string, avoiding the problem of precision caused by floating-point number storage when converting to decimal.
- PREC: The preceding Len function is the length of the integer part, followed by 3 is the number of decimal digits reserved.
- ROUNDING:ROUND_HALF_UP indicates rounding.
[Python] Round function