How to format number with zero-prefix

Let’s presume you want to format number to have ‘0’ prefix.

Example problem:
PRICE = 100
Required output = 00000100
or
PRICE = -100
Required output = -0000100

*----------------------------------------------------------------------*
*       CLASS lcl_format DEFINITION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
class lcl_format definition.
  public section.
    class-methods:
      format_with_zeros
        importing
          value(i_in) type numeric
       changing
          c_out     type csequence.
  protected section.
  private section.
endclass.                    "lcl_format DEFINITION
*----------------------------------------------------------------------*
*       CLASS lcl_format IMPLEMENTATION
*----------------------------------------------------------------------*
*
*----------------------------------------------------------------------*
class lcl_format  implementation.
  method format_with_zeros.
    data: l_width type i.

    describe field c_out length l_width in character mode.
    if i_in < 0.
      c_out = |-{ abs( i_in ) align = right pad = '0' width = l_width - 1 }|.
    else.
      c_out = |{ i_in align = right pad = '0' width = l_width }|.
    endif.
  endmethod.                    "format_with_zeros
endclass.                    "lcl_format IMPLEMENTATION

start-of-selection.
  data: l_num type dec10,
        l_out type char10.

  l_num = 10.
  lcl_format=>format_with_zeros( exporting i_in = l_num changing c_out = l_out ).
  write / l_out.
  l_num = -10.
  lcl_format=>format_with_zeros( exporting i_in = l_num changing c_out = l_out ).
  write / l_out.

Leave a Reply