Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't?
<p>I know that most decimals don't have an exact floating point representation (<a href="http://stackoverflow.com/questions/588004">Is floating point math broken?</a>).</p>

<p>But I don't see why <code>4*0.1</code> is printed nicely as <code>0.4</code>, but <code>3*0.1</code> isn't, when
both values actually have ugly decimal representations:</p>

<pre><code>&gt;&gt;&gt; 3*0.1
0.30000000000000004
&gt;&gt;&gt; 4*0.1
0.4
&gt;&gt;&gt; from decimal import Decimal
&gt;&gt;&gt; Decimal(3*0.1)
Decimal('0.3000000000000000444089209850062616169452667236328125')
&gt;&gt;&gt; Decimal(4*0.1)
Decimal('0.40000000000000002220446049250313080847263336181640625')
</code></pre>

<p>Here's a simplified conclusion from other answers.</p>

<blockquote>
  <p>If you check a float on Python's command line or print it, it goes through function <code>repr</code> which creates its string representation.</p>
  
  <p>Starting with version 3.2, Python's <code>str</code> and <code>repr</code> use 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.</p>
  
  <p>This scheme guarantees that value of <code>repr(float(s))</code> looks nice for simple
  decimals, even if they can't be
  represented precisely as floats (eg. when <code>s = "0.1")</code>.</p>
  
  <p>At the same time it guarantees that <code>float(repr(x)) == x</code> holds for every float <code>x</code></p>
</blockquote>

python floating-point rounding floating-accuracy ieee-754