Mich Dart
Mich Dart

Reputation: 2422

Ruby: leading zeros with already formatted string

I can't understand why this happens:

s = "000301"
"%06d" % s             ====> "000193"
sprintf("%06d", s)     ====> "000193"

Upvotes: 0

Views: 673

Answers (1)

KARASZI István
KARASZI István

Reputation: 31467

Because it was interpreted as an octal number.

Try it in irb:

> 0301
=> 193

But when you write:

> 301
=> 301

If you want to make it work, try to convert it to integer with String#to_i:

"%06d" % s.to_i
sprintf("%06d", s.to_i)

Upvotes: 5

Related Questions