I know that most decimals don\'t have an exact floating point representation (Is floating point math broken?).
But I don\'t see why 4*0.1 is printed nic
Here's a simplified conclusion from other answers.
If you check a float on Python's command line or print it, it goes through function
reprwhich creates its string representation.Starting with version 3.2, Python's
strandrepruse a complex rounding scheme, which prefers nice-looking decimals if possible, but uses more digits where necessary to guarantee bijective (one-to-one) mapping between floats and their string representations.This scheme guarantees that value of
repr(float(s))looks nice for simple decimals, even if they can't be represented precisely as floats (eg. whens = "0.1").At the same time it guarantees that
float(repr(x)) == xholds for every floatx