0

Using Bash in terminal on my Mac High Sierra.

So this code is supposed to ensure a three digit number. I did this with printf. I created bash file. This will take in a number and then convert it to three digits and print. But it does some weird stuff and I would like to know why.

If you type in normal numbers 1, 2, 3, ... everything works fine. If you type in three digit numbers 001 ... 007 everything works fine.

Examples:

  • Input 1 Output 001.
  • Input 04 Output 004.
  • Input 005 Output 005.

So far so good.

Now this is where it gets weird.

  • If I input 008 then it outputs 000.
  • If I input 009 then it outputs 000.
  • If I input 010 then it outputs 008.
  • If I input 019 then it outputs 000.
  • If I input 030 then it outputs 024.
number=$1
digit=$(printf "%03d" $number)
echo num: $number
echo digit: $digit
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
DonCoryon
  • 13
  • 2

1 Answers1

0

When you input a number with a leading 0, it treats it as an octal (i.e. base 8) number (so 010 -> 8 decimal). It will print in decimal, and your format arg says to print a width of 3 (so it prints 008).

The reason 009 prints 000 is because 9 is not a digit in octal (only 0-7), so the number is just ignored, so it prints 0 with a width of 3 (000).

Alejandro C.
  • 3,771
  • 15
  • 18