convert "1" to "001"

convert "1" to "001"

GeryKnee
Advocate Advocate
543 Views
6 Replies
Message 1 of 7

convert "1" to "001"

GeryKnee
Advocate
Advocate

Hi,

Is there a better syntax to convert "1" to "001" ?


(defun c:xx ( / TempSt)
(setq TempSt(itoa 1))
(while (< (strlen TempSt) 3)
(setq TempSt(Strcat "0" TempSt))
)
(princ TempSt)
(princ)
)

Thanks,

Gery

0 Likes
544 Views
6 Replies
Replies (6)
Message 2 of 7

calderg1000
Mentor
Mentor

Regards @GeryKnee 

Maybe this...

(defun xx (n)
  (setq n (strcat "00" (itoa n)))
)
(xx 1)

 


Carlos Calderon G
EESignature
>Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.

0 Likes
Message 3 of 7

CodeDing
Advisor
Advisor

I mean, there's only a couple scenarios here, perhaps this

 

 

(setq n "1")
(setq sLen (strlen n))
(setq n
  (strcat
    (cond ((= 1 sLen) "00") ((= 2 sLen) "0") (t ""))
    n
  );strcat
);setq

 

 

...even better, just remembered this lil gem:

 

(setq TempSt (itoa 1))
(setq TempSt (strcat (substr "00" (strlen TempSt)) TempSt))

 

 

0 Likes
Message 4 of 7

kpblc2000
Advisor
Advisor

(_kpblc-string-align 1 3 "0" 3 t)

Link to my functions library is in my sign.

Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям! | Do you find the posts helpful? "LIKE" these posts!
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.


Алексей Кулик aka kpblc | Aleksei Kulik aka kpblc Facebook | LinkedIn
autolisp.ru
Техническая поддержка программистов Autodesk в СНГ
Библиотека пользовательских lisp-функций | Custom Lisp-function library

0 Likes
Message 5 of 7

ВeekeeCZ
Consultant
Consultant

No, there is no built-in function for that.

So since the goal is quite simple I think any algorithm that works and you understand would be good enough.

0 Likes
Message 6 of 7

Kent1Cooper
Consultant
Consultant

@GeryKnee wrote:

Is there a better syntax to convert "1" to "001" ? ....


I assume from your posted code that you are not just talking about adding two 0's as at least one reply assumes, but that you will have a target number of characters and want to "pad" a string with leading zeros until it reaches the right length.  This is a topic that has come up numerous times.  Search for things like "leading zeros" or "pad with zeros," and you will find lots of suggestions and approaches.

Kent Cooper, AIA
0 Likes
Message 7 of 7

ronjonp
Mentor
Mentor

I'd think you'd want to check your largest number so that the padding can be adjusted for it:

;; Get length of largest integer
(setq p (apply 'max (mapcar 'strlen (setq l '("1" "10" "100" "1000" "10000")))))
;; ("00001" "00010" "00100" "01000" "10000") 
(mapcar '(lambda (x) (setq n "") (repeat (- p (strlen x)) (setq n (strcat n "0"))) (strcat n x)) l)
0 Likes