Add leading ZERO with ABAP

Add leading ZERO with ABAP


DATA : lw_char10 TYPE char10,
       lw_vbeln  TYPE vbeln.

lw_char10 = '300841'.

UNPACK lw_char10 TO lw_vbeln.  " ==> LW_VBELN = 0000300841

You can also use FM CONVERSION_EXIT_ALPHA_INPUT :


CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
 EXPORTING
   INPUT = lw_vbeln     " ==> LW_VBELN = 300841
 IMPORTING
   OUTPUT = lw_vbeln.   " ==> LW_VBELN = 0000300841

Another method that can be used to add leading zero in ABAP variables is using OVERLAY statement.
Here is an example where “SHIFT … RIGHT DELETING TRAILING SPACE” is used with “OVERLAY … WITH …” for zero padding.

The first ABAP statement “SHIFT lv_vbeln RIGHT DELETING TRAILING SPACE” will change the lv_vbeln value as ‘ 300841’ with four preceding space characters.
And the second command “OVERLAY lv_vbeln WITH ‘0000000000’” will replace the space characters in lv_vbeln with zero characters.

What is important here is the number of zeros in the Overlay pattern.
The number of zero characters must be as character length of the ABAP variable.


DATA : lw_char10 TYPE char10,
       lw_vbeln  TYPE vbeln.

lw_char10 = '300841'.

lw_vbeln = lw_char10.
SHIFT lw_vbeln RIGHT DELETING TRAILING SPACE.
OVERLAY lw_vbeln WITH '0000000000'.

Source: http://www.kodyaz.com/articles/zero-padding-in-abap-how-to-add-leading-zeros.aspx

New way since ABAP 7.40 (thanks Michael) :


DATA lv_orderno TYPE char10 VALUE '875545'.
lv_orderno = |{ lv_orderno_2 ALPHA = IN }|.

WRITE lv_orderno. " Result ‘0000875545’

Short link: goo.gl/X9UXnn

About the author

fjourneau administrator

Hi, I'm Florian Journeau, SAP ABAP R3 Freelance, based in Toulouse, France. You want to know more about me, have a look on my CV : cv.fjourneau.net.

5 Comments so far

KrakenPosted on4:13 pm - Mar 31, 2020

lw_char10 not lv_char10, you have a typo

Adriano BaptistaPosted on3:03 pm - Aug 19, 2021

Thanks!
Very simple and objective.

MichaelPosted on4:35 pm - Nov 14, 2023

Hey Florian,

maybe you like to add this one:

DATA lv_orderno TYPE char10 VALUE ‘875545’.
lv_orderno = |{ lv_orderno_2 ALPHA = IN }|.
WRITE lv_orderno.

result ‘0000875545’

Leave a Reply