ABAP stop rounding when using FOR with REDUCE

Viewed 566

I am trying to sum amount using FOR and REDUCE...How do we stop rounding when using FOR with REDUCE... example 404120.71 gets rounded to 404121.000

data(lv_total_sum) = reduce tslxx9( 
      init x = 0 
      for wa in lt_table
      next x = x + wa-zzamount ).
1 Answers

The variables in the INIT "block" are typed either explicitly or implicitly.

In your case, you assigned 0 so it's assigning implicitly the type integer (it's why you don't get the decimals):

data(lv_total_sum) = reduce tslxx9( init x = 0 for wa in lt_table next x = x + wa-zzamount ).

If you want to assign a type explicitly, you can do it this way:

data(lv_total_sum) = reduce tslxx9( init x TYPE tslxx9 for wa in lt_table next x = x + wa-zzamount ).

With TYPE, the variable is assigned the initial value by default.

See the ABAP documentation for more information about REDUCE.

EDIT: complementary solutions:

  • In some cases, you may want to assign a non-initial value, like 10 below, you may then use CONV to assign a type :
    data(lv_total_sum) = reduce tslxx9( init x = CONV tslxx9( 10 ) for wa in lt_table next x = x + wa-zzamount ).
    
  • When dealing with decimals, you may simply choose the biggest numeric decimal type possible, which is decfloat34 (you may also choose a smaller one, decfloat16):
    data(lv_total_sum) = reduce tslxx9( init x TYPE decfloat34 for wa in lt_table next x = x + wa-zzamount ).
    
Related