Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Okay, two parts:</p> <p>first, to format a number:</p> <pre><code>"{number:06}".format(number=100) </code></pre> <p>will give you <code>'000100'</code>. But before that, we have to round. </p> <p><strong>EDIT:</strong> This solution is much more elegant:</p> <pre><code>import math def rep(number): rounded = 10**(math.floor(math.log(number,10)-math.log(0.5,10))) return "{number:06}".format(number=int(rounded)) </code></pre> <p>Let's see:</p> <pre><code>&gt;&gt;&gt; print rep(100) 000100 &gt;&gt;&gt; print rep(1000) 001000 &gt;&gt;&gt; print rep(501) 001000 &gt;&gt;&gt; print rep(499) 000100 &gt;&gt;&gt; print rep(500) 000100 </code></pre> <p><strong>OLD Version for future reference end educational delight</strong>:</p> <p>(It's still faster as it doesn't involve any <code>log</code> operations)</p> <p>Here's a neat little trick: <code>round(501)</code> will round to the first decimal digit, but <code>round(501, -1)</code> will round to the <code>10^1</code> digit (so the result is <code>500.0</code>), <code>round(501, -2)</code> to the <code>10^2</code> (the result still being <code>500.0</code>), and <code>round(501, -3)</code> will round up to 1000.</p> <p>So we want 500 to be rounded up to 1000, but 53 to be rounded up to 100. Well, here's how we do it:</p> <pre><code>number = 521 rounded = round(number, -len(str(number))) </code></pre> <p>So, since the string describing <code>number</code> is three characters long, we round to -3.</p> <p>However, this rounds up perfectly, but if we're rounding down, it always rounds down to 0. Let's just catch this case:</p> <pre><code>def rep(number): rounded = round(number, -len(str(number))) if not rounded: # 0 evaluates to False rounded = 10**(len(str(number))-1) return "{number:06}".format(number=int(rounded)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload