Question Krishnaveni Kapu · Sep 16, 2024

padding zeros to the desired length

I receive a number as input

length = ln = 7

if input = 25
I need to add zeros to make make it as - 0000025 (a total length of ln)

if input = 9
I need to add zeros to make make it as - 0000009 (a total length ofln)

Comments

Enrico Parisi · Sep 16, 2024

Many ways to do it, my way:

USER>Set input=25 
USER>Set ln=10 
USER>Set $Piece(Pad,"0",ln-$Length(input))="0" 
USER>Set Padded=Pad_input 
USER>Write
 
Pad="00000000"
Padded="0000000025"
input=25
ln=10
0
Robert Cemper · Sep 16, 2024
write$translate($justify(input,ln)," ",0)
0
Julius Kavay · Sep 16, 2024

Assuming, your input value is an integer, you have , along with the other solutions, one more:

// this works as long as len  < 145//set len =  120set inp = 12345write$e(1E120_inp,*-len+1,*)

// of course, if the len is shorter than, say 10,// then you can use smaller constans like//set len=10set inp=9write$e(1E10_inp,*-len+1,*)

A good (or even a bad) side effect of the above solution is, if you get an input value which is LONGER than the length, it will be truncated to the given length

0
Hannah Sullivan · Sep 17, 2024

Another possible solution to this,

ClassMethod PadNumberWithZeros(number As%String, ln As%Integer) As%String
{
    set num = number
    while$length(num) < ln {
        set num = "0" _ num
    }
    return num
}

Returns 0000025  for 25 and 0000009 for 9 for the provided test cases

0
Stuart Salzer · Sep 18, 2024

The object script expression: $TRANSLATE($JUSTIFY(input,length)," ","0")

0