How to add trailing zeros in SAP ABAP?

If you find yourself in a situation where you need to add trailing zeros you can use one of the following methods:

Method 1. Using a while loop:

[cce lang="abap"]
DATA variable TYPE c LENGTH 16 VALUE '123'.
DATA string_length TYPE i.
DATA type_length TYPE i.
DATA counter TYPE i.

DESCRIBE FIELD variable LENGTH type_length IN CHARACTER MODE.

string_length = type_length - strlen( variable ).

WHILE  counter  <  string_length.
   counter  =  counter  + 1.
  CONCATENATE variable '0' INTO variable.
ENDWHILE.
[/cce]

In this method, you need 3 additional temp variables and few operations.


Method 2. Using a TRANSLATE keyword:

[cce lang="abap"] 
DATA variable TYPE c LENGTH 16 VALUE '123'.

TRANSLATE variable USING ' 0'.
[/cce] 

In this method, you don’t need any additional variables. Furthermore its only one line of code and it’s three-time faster than method 1.

Written by 

Leave a Reply

Your email address will not be published. Required fields are marked *