Left-aligned zero-padding
Asked Answered
A

2

5

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          "
Alasteir answered 18/11, 2014 at 20:45 Comment(3)
0-padding on the right changes the value, this operation does not look usefulBranch
You're close with the last example, but you need some more commas, because the pad char is the last of four arguments, and you're giving 0 as the second argument.Unflinching
@Branch 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.Unflinching
U
6

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

Unflinching answered 19/11, 2014 at 2:35 Comment(0)
B
5

Use ~A:

(format nil "~33,,,'0A" 27)
==>  "270000000000000000000000000000000"
Branch answered 18/11, 2014 at 22:35 Comment(1)
This can be done with ~a, but tilde-less-than (which OP is already using) works, too. The important part (more commas) is the same, though.Unflinching

© 2022 - 2024 — McMap. All rights reserved.