Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left-aligned zero-padding

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          "
like image 411
Inaimathi Avatar asked Nov 18 '14 20:11

Inaimathi


2 Answers

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

like image 69
Joshua Taylor Avatar answered Oct 05 '22 00:10

Joshua Taylor


Use ~A:

(format nil "~33,,,'0A" 27)
==>  "270000000000000000000000000000000"
like image 40
sds Avatar answered Oct 05 '22 01:10

sds