Question

So if this "%05d" % 123 returns #=> "00123", I would expect "%05d" % 0123 to return #=> "00123" as well, but instead it returns #=> "00083". Why is this so?

Was it helpful?

Solution

Numbers starting with 0 are interpreted as octal, just like numbers starting with 0x are interpreted as hexadecimal. 83 is represented as 123 in octal.

irb(main):001:0> 0123
=> 83
irb(main):002:0> 1*8**2 + 2*8**1 + 3*8**0
=> 83
irb(main):003:0> "%05d" % 0x7b
=> "00123"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top