Recently there is a need to show the number as a fixed number of digits, the number of digits in the front with 0 supplements
Like 5-bit:
Copy Code code as follows:
3-> 00003
292-> 00292
12422-> 12422
It's easy to find Ruby.
Copy Code code as follows:
Irb> "%05d"% 12422
"12422"
Irb> "%05d"% 22
"00022"
The above approach is basically standard practice. If you are working with strings directly, you can also use String#rjust:
"12422". Rjust (5, ' 0 ') => "12422"
"Rjust" (5, ' 0 ') => "00022"
Attached: Another article
In the project, we used the algorithm of the string to fill zero, and finally found that rails has this function can be implemented, eliminating unnecessary trouble, the example should be very easy to understand
Copy Code code as follows:
>>> A = 22
>>> s = str (a). Rjust (4, ' 0 ')
>>> Print S
0022
>>> A = 2222
>>> s = str (a). Rjust (4, ' 0 ')
>>> Print S
2222