Mac Ruby 2.6.5
If the standard input number is less than the specified number of digits, 0 is added left-justified. Example) In the case of 8 digits 3→00000003 12→00000012 1234→00001234
Use the printf method. The format is specified by the first argument, the character string or numerical value given by the subsequent arguments is formatted according to the format, and the character string is generated and output. The basic printf method format is as follows.
printf ("% [flag] [width] [.precision] [indicator]", [string or number])
There are various flags, but if you use "0", the extra digits when specifying the width will be filled with "0". Width specifies the number of digits to be displayed. (Accuracy is not specified this time)
There are various directives (instructing how to format given data), but when displaying an integer in decimal notation, use % d
.
For example, in the above example:
num = gets.to_i
printf ("% 08d", num) #Enter "0" for the flag, "8" for the width, and "% d" for the specifier
# When num = 3
=> "00000003"
# When num = 12
=> "00000012"
Recommended Posts