Greggy D
Greggy D

Reputation: 121

How to control the number of digits when printing numbers?

I need assistance with a code, the final answer needs to be 6 characters, I am asking the person for a number, they can enter the following:

 1, 10, 100, 1000, 10000

What I need is the final number to be 6 characters long so this is the answers for each of the numbers

1     => 000001
10    => 000010
100   => 000100
1000  => 001000
10000 => 010000

So I need to set the length at 6 digits, enter the number and add "0" to the front until it is 6 digits.

How can I do that?

Additional to this if someone enters 200 I need it to round down to 100 and if they enter 501 it rounds up to 1000; can this also be done?

Upvotes: 0

Views: 13730

Answers (4)

Manuel Ebert
Manuel Ebert

Reputation: 8509

Okay, two parts:

first, to format a number:

"{number:06}".format(number=100)

will give you '000100'. But before that, we have to round.

EDIT: This solution is much more elegant:

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))

Let's see:

>>> print rep(100)
000100
>>> print rep(1000)
001000
>>> print rep(501)
001000
>>> print rep(499)
000100
>>> print rep(500)
000100

OLD Version for future reference end educational delight:

(It's still faster as it doesn't involve any log operations)

Here's a neat little trick: round(501) will round to the first decimal digit, but round(501, -1) will round to the 10^1 digit (so the result is 500.0), round(501, -2) to the 10^2 (the result still being 500.0), and round(501, -3) will round up to 1000.

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:

number = 521
rounded = round(number, -len(str(number)))

So, since the string describing number is three characters long, we round to -3.

However, this rounds up perfectly, but if we're rounding down, it always rounds down to 0. Let's just catch this case:

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))

Upvotes: 8

zrslv
zrslv

Reputation: 1846

>>> print "%06d" % 1
000001
>>> print "%06d" % 10
000010
>>> print "%06d" % 100
000100
>>> print "%06d" % 1000
001000
>>> print "%06d" % 10000
010000
>>> print "%06d" % 100000
100000

5.6.2. String Formatting Operations

Upvotes: 1

user1129682
user1129682

Reputation: 1091

For completeness's sake:

>>> for i in range(6):
...   "%06d" % 10**i

will print

'000001'
'000010'
'000100'
'001000'
'010000'
'100000'

Upvotes: 1

San4ez
San4ez

Reputation: 8231

zfill also can help you

>>> str(10).zfill(6)
'000010'

Upvotes: 4

Related Questions