Is there a easy way to format a given Integer to a String with fixed length and leading zeros?
# convert numbers to strings of fixed length 3
[1, 12, 123, 1234].map { |e| ??? }
=> ["001", "012", "123", "234"]
I found a solution but maybe there is a smarter way.
format('%03d', e)[-3..-1]
How about getting the last three digits using % 1000
instead of doing string manipulations?
[1, 12, 123, 1234].map { |e| format('%03d', e % 1000) }
As suggested by the Tin Man in the comments, the original version is better in terms of readability and only abount 1.05x slower than this one, so in most cases it probably makes sense to use that.
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