Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Trailing zeroes to an integer

I have a positive integer variable which can have values between 0 to 999. This integer is then passed to a software.

To pass into this software the integer should always be 3 digits. But the problem is, it should have trailing zeroes.

For example:

1 should be passed as 100
19 should be passed as 190
255 should be passed as 255

It can be done by checking the length of the variable and multiplying with 10 or 100 depending on the length. But is there any better Python alternative. Also this doesn't work for value 0.

(Note: Trailing Zeroes is because the integer value is actually a millisecond value. The software reads the values digit by digit and it always needs 3 digits)

like image 506
Saravana Murthy Avatar asked Nov 28 '22 20:11

Saravana Murthy


2 Answers

You don't even need the formatting operators for this, just plain str methods. To right justify with zeroes:

x.zfill(3)

To left justify with zeroes:

x.ljust(3, '0')

You'd need to wrap x in str first in this scenario if x is currently an int. At that point, it may be worth just using the formatting operators as others have suggested to directly produce the final str, with no intermediate str, when justification is required.

like image 181
ShadowRanger Avatar answered Dec 06 '22 16:12

ShadowRanger


I don't know why the zeros got chopped off (ideally you should fix the source of the problem), but you can format the numbers as strings and then turn them back into ints:

numbers = [1, 19, 255]
numbers = [int('{:<03}'.format(number)) for number in numbers]

This left-aligns each number with <, in a field 3 characters wide, filling extra characters with 0.

like image 42
TigerhawkT3 Avatar answered Dec 06 '22 14:12

TigerhawkT3