Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string for zero padding decimal with sign in front?

Is there a format string for zero padding a decimal with the sign in front?

(format nil ? 5) => "+0005"
(format nil ? -5) => "-0005"

The closest I found was

(format nil "~4,'0@d" 5) => "00+5"
(format nil "~4,'0@d" -5) => "00-5"
like image 782
Sam Avatar asked Mar 14 '23 07:03

Sam


1 Answers

This is a draft of a custom printer function:

(defun signed-padding (stream data colonp atsignp &optional (padding 0))
  (declare (ignore colonp atsignp))
  (format stream "~:[+~;-~]~v,'0d" (minusp data) padding (abs data)))

...and an example:

(values
 (format nil "~v/signed-padding/" 20 330)
 (format nil "~5/signed-padding/" -4))

"+00000000000000000330"
"-00004"

You could probably add more checks and options.

like image 118
coredump Avatar answered Apr 27 '23 11:04

coredump