Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad a number with zeros to a specific length in tcl?

I need to pad a number with a specific length (say 8) where the input number could be of any length.

Example: If the input number is 123456, I want to pad it as 12345600

If I knew that all input numbers would be of the same length (say 6), I would have done something like

[format "$input_num%02d" 0]

But since the input number can be of varied length, how do I achieve this? Obviously the below didn't work:

set cur_length [expr[llength[split $input_num ""]]
set padding [expr 8 - $cur_length]
set padded_num [format "$input_num%${padding}d" 0]

Any help is appreciated.

Thanks.

like image 562
Tcl_newbie Avatar asked Dec 05 '25 10:12

Tcl_newbie


1 Answers

It's really simple, actually:

format %-08s $input_num

A number is also a string, so it can be left-justified like a string.

Documentation: format

like image 68
Peter Lewerin Avatar answered Dec 10 '25 10:12

Peter Lewerin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!