There's a format
directive to zero-pad digits.
cl-user> (format nil "~12,'0d" 27)
"000000000027"
and there's a similar-ish directive to left-align strings while padding them
cl-user> (format nil "~12@<~d~>" 27)
"27 "
Is there a way to do both? That is:
cl-user> (format nil "~12,something,d" 27)
"270000000000"
The naive "~12,'0@<~d~>"
does not seem to do what I want here.
cl-user> (format nil "~12,'0@<~d~>" 27)
"27 "
You're close with the last example, but you need some more commas, because tilde less-than takes four arguments, and the pad char is the fourth arguments, but you're passing it as the second. Just pass it as the fourth:
CL-USER> (format nil "~12,,,'0@<~d~>" 27)
"270000000000"
As an aside, it was pointed out in the comments that right padding changes the value that that doesn't seem like a useful operation. I'd say that it can be a useful operation. It might depend on whether these are integers or strings where the values happen to be digit characters. I've seen maintenance systems where upgrades have changed field width and the procedure for migrating old records is to right pad with 0's. The right padding was precisely because it changes the value. 000027 (six chars) can be written as 27, which isn't six chars wide, and 000027 could also be accidentally read (probably by machine, when a programmer isn't careful) as an octal. 270000, on the other hand, has to be six-digits, and won't be octal, since it doesn't start with a 0
Use ~A
:
(format nil "~33,,,'0A" 27)
==> "270000000000000000000000000000000"
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