How do i reduce decimal places in python?

TLDR ;]

The rounding problem of input and output has been solved definitively by Python 3.1 and the fix is backported also to Python 2.7.0.

Rounded numbers can be reversibly converted between float and string back and forth:
str -> float[] -> repr[] -> float[] ... or Decimal -> float -> str -> Decimal

>>> 0.3
0.3
>>> float[repr[0.3]] == 0.3
True

A Decimal type is not necessary for storage anymore.

Results of arithmetic operations must be rounded again because rounding errors could accumulate more inaccuracy than that is possible after parsing one number. That is not fixed by the improved repr[] algorithm [Python >= 3.1, >= 2.7.0]:

>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1, 0.2, 0.3
[0.1, 0.2, 0.3]

The output string function str[float[...]] was rounded to 12 valid digits in Python < 2.7x and < 3.1, to prevent excessive invalid digits similar to unfixed repr[] output. That was still insufficientl after subtraction of very similar numbers and it was too much rounded after other operations. Python 2.7 and 3.1 use the same length of str[] although the repr[] is fixed. Some old versions of Numpy had also excessive invalid digits, even with fixed Python. The current Numpy is fixed. Python versions >= 3.2 have the same results of str[] and repr[] function and also output of similar functions in Numpy.

Test

import random
from decimal import Decimal
for _ in range[1000000]:
    x = random.random[]
    assert x == float[repr[x]] == float[Decimal[repr[x]]]  # Reversible repr[]
    assert str[x] == repr[x]
    assert len[repr[round[x, 12]]] 

Chủ Đề