Search code examples
abapnetweaver

Why is precision lost if resolving of the type left to the compiler?


What is the reason of the lost of precision if the decimal type of the variable is left to be defined by the compiler? Is this documented anywhere?

DATA: gv_1 TYPE p LENGTH 15 DECIMALS 2 VALUE '56555.31'.
DATA: gv_2 TYPE p LENGTH 15 DECIMALS 2 VALUE '56555.31'.
DATA: gv_3 TYPE p LENGTH 15 DECIMALS 2 VALUE '56555.34'.

DATA(gv_sum) = gv_1 + gv_2 + gv_3. "data type left to be resolved by the compiler

WRITE / gv_sum.

DATA: gv_sum_exp TYPE p LENGTH 15 DECIMALS 2. "explicit type declaration
gv_sum_exp = gv_1 + gv_2 + gv_3.

WRITE / gv_sum_exp.

The first sum results in

169666

The second one in

169665.96


Solution

  • As we know, the ABAP compiler brings all the operands of an arithmetic expression to the so-called calculation type. And we also know that data type with the largest value range determines the whole caclulation type.
    But you, probably, don't aware of some changes that were introduced to this process with the release of inline declarations in ABAP. Here they are:

    If operands are specified as generically typed field symbols or formal parameters and an inline declaration DATA(var) is used as the target field of an assignment, the generic types contribute to the statically detectable calculation type (used to determine the data type of the declaration) as follows:
    ...
    csequence, clike, c, n, and p like p. If no type with a higher priority is involved, the type p with length 8 (no decimal places) is used for the declaration.
    ...

    That is exactly what we see in debugger during execution of your code:

    enter image description here