I want to pad zeroes to the right side of a given number using sprintf
.
Example: if the number is 0715
then I want to pad zeroes to the right side creating a new six-digit number:
Input-->0715
Output-->071500
There is no pattern for sprintf
to format a string left-justified with zeroes instead of spaces.
These are all the flags that perldoc lists:
space prefix non-negative number with a space + prefix non-negative number with a plus sign - left-justify within the field 0 use zeros, not spaces, to right-justify # ensure the leading "0" for any octal, prefix non-zero hexadecimal with "0x" or "0X", prefix non-zero binary with "0b" or "0B"
If you insist on using sprintf
, you will have to go with -
to left-justify within the field, which will give you blank spaces on the right. Then you need to change those to zeroes. You can do that with the tr
transliteration operator. I'm using the shorter form with the /r
modifier that makes tr///
return the value instead of just changing the lvalue $foo
.
my $foo = '0715';
print sprintf('%-6s', $foo) =~ tr/ /0/r;
Output:
071500
You can also do it using substr
. Append six 0
s and get the string from 0th
to 6th
index. But obviously as Sobrique said you can't do it treating it as number.
my $num = '0715';
print substr $num.'0'x6,0,6;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With