Expressions, Operators and Assignments

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Almost every ABAP program moves values from one variable to another, calculates with them and then asks a yes-or-no question about the result. This page explains how that works in plain terms: how a calculation picks the kind of arithmetic it uses, what happens to a value when it is stored in a variable of a different type, how rounding is applied, and how comparisons and tests are written. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). Everything here applies both to ABAP Cloud and to classic, Standard ABAP only, code on premise; the few older statements that are still found in classic programs are listed in a separate section and are marked as such. After reading it you can predict the result of a calculation with decimals, avoid the usual rounding and conversion surprises, and write clear conditions. The examples use the Expense claims running example (the tables ZEXP_CLAIM and ZEXP_ITEM) and simple generic values.

Before you read

Key terms

  • Calculation type: the data type in which ABAP carries out an arithmetic expression, chosen from the types of its operands.

  • Conversion rule: the rule that decides how a value of one data type is changed into another when it is assigned.

  • Commercial rounding: rounding in which a value exactly halfway between two results goes away from zero.

  • Relational expression: a comparison of two operands, such as a < b, that is either true or false.

  • Predicate expression: a test on a single operand, such as IS INITIAL, that is either true or false.

  • Initial value: the value a data object has before anything is assigned to it, such as zero for a number and blanks for text.

Assignments

An assignment copies the value on the right of an equals sign into the variable on the left, converting it when the types differ. The right side can be a data object or the result of a calculation, a function call or a constructor expression. The listing requires no SAP system and runs in the local playground; it printed 0000004711, 250.00 and 0.

REPORT zp_asg.

DATA claim_no TYPE n LENGTH 10.
DATA copy_no  TYPE n LENGTH 10.

claim_no = 4711.
copy_no  = claim_no.
WRITE / |{ copy_no }|.

DATA total TYPE p LENGTH 15 DECIMALS 2.
total = 100.
total += 25.
total *= 2.
WRITE / |{ total }|.

DATA(count) = 0.
WRITE / |{ count }|.

A calculation assignment with +=, -=, *= or /= combines an operator with the assignment. As long as the right side is not a constructor expression using #, total += amount has the same effect as total = total + ( amount ), and the right side is put in parentheses first. Calculation assignments are standalone statements only, accept numeric operands (not text), and do not allow an inline declaration on the left. Casting assignments for object references and the copying of same-named structure components are covered with the pages on classes and on structures.

The inline declaration DATA( ) combines the declaration and the assignment: DATA(count) = 0 creates count with the type of the value on the right, so the literal 0 gives an integer, not a decimal amount. When you want a given type, declare the variable first or use CONV.

Arithmetic and the calculation type

An arithmetic expression combines numeric operands with operators. Within one level of parentheses, an operator of higher priority is applied before one of lower priority, and adjacent operators of the same priority are applied in the order shown:

Operator Meaning Priority Order

**

Left operand raised to the power of the right

3 (highest)

right to left

*, /, DIV, MOD

Multiplication, division, integer part of the quotient, non-negative remainder

2

left to right

+, -

Addition, subtraction

1 (lowest)

left to right

DIV and MOD are consistent with each other: 7 DIV 3 is 2 and 7 MOD 3 is 1, while -7 DIV 3 is -3 and -7 MOD 3 is 2, because the remainder is never negative. Operators and parentheses are separated from their operands by at least one blank: write ( a + b ) * c, never (a+b)*c. A + or - can also stand in front of a single operand. Dividing by zero raises a catchable exception, except when the dividend is also 0, in which case the result is 0. A result outside the range of the calculation type raises CX_SY_ARITHMETIC_OVERFLOW; both can be caught with TRY and CATCH.

Before ABAP calculates anything it determines the calculation type, the data type in which the whole expression is carried out. It comes from the types of all operands together and, when the result goes into an existing variable, also from the type of that variable. The rules are applied in decreasing priority:

  1. If any operand is of type decfloat16 or decfloat34, the calculation type is decfloat34.

  2. Otherwise, if any operand is of type f, or the operator ** is used, it is f.

  3. Otherwise, if any operand is of type p, it is p.

  4. Otherwise, if any operand is of type int8, it is int8.

  5. Otherwise, if any operand is of type i (or b or s), it is i.

Operands of type c, n and string count as p, and d, t, x and xstring count as i. The operator ** gives decfloat34 when a decimal floating point operand is involved and f otherwise; the built-in function ipow avoids f for integer exponents. If the target is an inline declaration and the calculation type is p, the declared variable is p with length 8 and no decimal places, so declare such a variable yourself or use CONV on the expression.

flowchart TD A[Operands and result variable of the expression] --> B{Any decfloat16 or decfloat34?} B -- yes --> R1[Calculate in decfloat34] B -- no --> C{Any type f, or the operator ** ?} C -- yes --> R2[Calculate in floating point f] C -- no --> D{Any type p?} D -- yes --> R3[Calculate in packed numbers p] D -- no --> E{Any type int8?} E -- yes --> R4[Calculate in int8] E -- no --> R5[Calculate in integers i]

The calculation type also fixes the rounding of interim results. With the types i, int8, p and decfloat34 each interim result that is not exact is rounded commercially, which differs from languages that cut off the decimals. The consequence that surprises newcomers most is integer division: when all operands are integers the calculation type is i, so 7 / 2 gives 4, not 3.5, and 1 / 3 + 1 / 3 + 1 / 3 gives 0 because each division is rounded to 0 first. If you want the decimal result, make one operand a decimal type with CONV.

Conversion rules

Whenever the type of the source differs from the type of the target, ABAP applies a conversion rule chosen for that pair of types. The rules are defined for every pair of elementary types; the ones that matter most in day-to-day work are these.

From and to What happens

p to i

The value is rounded commercially to a whole number; if it does not fit, CX_SY_CONVERSION_OVERFLOW is raised.

decfloat or f to i

The value is rounded to a whole number, with the same exception when it does not fit.

p, decfloat or f to a p with fewer decimal places

The value is rounded to the decimal places of the target; for a p source the rounding is commercial.

c to a number

The text must hold a number, otherwise CX_SY_CONVERSION_NO_NUMBER is raised; a field with only blanks counts as zero.

i or p to c

The number is written right-aligned with a sign position. If the field is too short the left side is cut off and * is set in the first position, so prefer a string template for output.

c to a shorter c

The text is cut off on the right.

i or p to n

Only the absolute value is kept, as a right-aligned string of digits padded with zeros on the left; if the field is too short the left digits are cut off.

The conversion rules of the keyword documentation list every pair of types, including the source types not shown here, and should be consulted whenever a conversion matters. In new code, make the conversion visible instead of leaving it implicit, with CONV, and use EXACT when a conversion must raise an exception instead of losing information.

Rounding

Commercial rounding is the rule applied when a value is stored with fewer decimal places. A value exactly halfway between two candidates goes to the one farther from zero, so 2.345 becomes 2.35 and -2.345 becomes -2.35. With the value, the number of decimal places kept and its sign, the result is:

For 2.345 and this gives .

The built-in function round rounds a decimal floating point number. It takes the value (val), either the number of decimal places (dec) or a precision (prec), and optionally a rounding mode (mode). The modes are the ROUND_... constants of the class CL_ABAP_MATH: round_half_up (commercial rounding, used when mode is omitted), round_half_down, round_half_even, round_up (away from zero), round_down (towards zero), round_ceiling and round_floor. The functions ceil, floor and trunc return whole numbers, frac the decimal places, and abs and sign the absolute value and the sign.

The first example calculates a value-added tax on a claim item. It requires no SAP system and runs in the local playground; it printed Tax 12.59 gross 72.56 and 7 / 2 = 4, 7 DIV 2 = 3, 7 MOD 2 = 1. The tax rate is a decfloat34, so the calculation runs in decfloat34 and is exact (59.97 times 0.21 is 12.5937); the rounding happens once, when the result is stored in the amount variable with two decimal places.

REPORT zp_tax.

TYPES ty_amount TYPE p LENGTH 15 DECIMALS 2.

DATA rate  TYPE decfloat34 VALUE '0.21'.
DATA net   TYPE ty_amount VALUE '59.97'.
DATA tax   TYPE ty_amount.
DATA gross TYPE ty_amount.

tax   = net * rate.
gross = net + tax.

DATA ratio TYPE i.
ratio = 7 / 2.

WRITE / |Tax { tax } gross { gross }|.
WRITE / |7 / 2 = { ratio }, 7 DIV 2 = { 7 DIV 2 }, 7 MOD 2 = { 7 MOD 2 }|.

The second example compares two rounding modes for the same value. It requires an SAP system; not run here. The comments give the values that follow from the mode definitions: 2.345 lies exactly halfway between 2.34 and 2.35, so half up chooses 2.35 and half even chooses 2.34, the candidate whose last digit is even.

DATA(up)   = round( val = CONV decfloat34( '2.345' ) dec = 2 mode = cl_abap_math=>round_half_up ).    " 2.35
DATA(even) = round( val = CONV decfloat34( '2.345' ) dec = 2 mode = cl_abap_math=>round_half_even ).  " 2.34

Relational expressions

A relational expression compares operands and is true or false. It stands wherever a logical expression is expected, such as the condition of IF or WHILE. The comparison operators have a symbol and a letter form:

Symbols Letters Meaning

=, <>

EQ, NE

Equal, not equal

<, >, <=, >=

LT, GT, LE, GE

Smaller, greater, smaller or equal, greater or equal

BETWEEN ... AND ...

The value lies in a closed interval, ends included

IN

The value satisfies a selection table (a range table)

CO, CN, CA, NA, CS, NS, CP, NP

Character-string comparisons: contains only, contains not only, contains any, contains not any, contains string, contains no string, conforms to a pattern, does not conform to a pattern

As with arithmetic, ABAP first decides a comparison type from the types of the operands and converts the operands to it; when a decimal floating point number is involved, the comparison is always carried out in decfloat34. Compare values of the same type whenever you can.

Conditions combine with NOT, AND and OR, and with parentheses, which should always be written when AND and OR appear together. The listing requires no SAP system and runs in the local playground; it printed needs a manager check and within the standard limit.

REPORT zp_rel.

DATA amount TYPE p LENGTH 15 DECIMALS 2 VALUE '480.00'.
DATA status TYPE c LENGTH 1 VALUE 'N'.

IF amount BETWEEN 100 AND 500 AND ( status = 'N' OR status = 'R' ).
  WRITE / 'needs a manager check'.
ENDIF.

IF NOT amount > 1000.
  WRITE / 'within the standard limit'.
ENDIF.

Predicate expressions

A predicate expression asks a question about the state of one operand.

  • IS INITIAL is true when the operand has its type-dependent initial value, whatever its type. It is the standard way to ask "was anything entered?" without naming the type.

  • IS BOUND is true when a reference variable points to an object or data object.

  • IS ASSIGNED is true when a field symbol is assigned to a memory area.

  • IS SUPPLIED is true inside a method when the caller passed an optional parameter.

  • IS INSTANCE OF is true when an object reference points to an object of the given class or interface.

  • The built-in predicate functions line_exists( ), contains( ) and matches( ) also act as predicates. line_exists( ) takes a table expression such as items[ claim_id = 7 ].

The listing requires no SAP system and runs in the local playground; it printed nothing was read, work with the item and route to a manager.

REPORT zp_pred.

TYPES: BEGIN OF ty_item,
         claim_id TYPE i,
         amount   TYPE p LENGTH 15 DECIMALS 2,
       END OF ty_item.
DATA items TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.
DATA claim_header TYPE ty_item.
DATA go_ref TYPE REF TO ty_item.

items = VALUE #( ( claim_id = 7 amount = '12.50' ) ).

IF claim_header IS INITIAL.
  WRITE / 'nothing was read'.
ENDIF.

GET REFERENCE OF items[ 1 ] INTO go_ref.
IF go_ref IS BOUND AND line_exists( items[ claim_id = 7 ] ).
  WRITE / 'work with the item'.
ENDIF.

DATA amount TYPE p LENGTH 15 DECIMALS 2 VALUE '1200.00'.
DATA(is_large) = xsdbool( amount > 1000 ).
IF is_large = abap_true.
  WRITE / 'route to a manager'.
ENDIF.

Flags have traditionally been variables of type abap_bool with the values abap_true ('X') and abap_false (' '). The functions xsdbool( ) and boolc( ) turn a condition into such a value: boolc returns a string, while the result of xsdbool has the ABAP type mapped to abap_boolean, so it is the one that fits a flag variable. The keyword documentation now marks both functions as obsolete and recommends Boolean value expressions and the data type B in new developments, so expect to read xsdbool in existing code.

Older material you may meet

Books and code written before release 7.40 use a different style, and Standard ABAP still accepts much of it. You will meet it in maintenance work:

  • MOVE a TO b does the same as b = a, and a leading COMPUTE is ignored by the assignment; the keyword documentation marks both as obsolete. Write the plain equals sign.

  • ADD 1 TO n, SUBTRACT, MULTIPLY and DIVIDE are old forms of n += 1, n -= 1, n *= 2 and n /= 2, and the documentation calls them obsolete.

  • Operators and relational words are often written in letter form (EQ, NE, GT) and long calculations were split into several statements because there were no inline declarations. Today a value is declared where it is first set, with DATA( ) or FINAL( ).

  • Flags were set with IF ... flag = 'X'. ELSE. flag = ' '. ENDIF. in four lines; xsdbool( ) replaces them with one.

  • The built-in functions round, ceil and floor make the rounding rule visible; older code often relies on the implicit rounding of an assignment instead.

Summary

  • An assignment with = copies a value and converts it by the conversion rule for the two types; +=, -=, *= and /= are the short forms of a calculation plus an assignment.

  • The calculation type is chosen from all operands and an existing result variable: decfloat34, then f, then p, then int8, then i. With only integers, 7 / 2 is 4; use DIV and MOD for the integer quotient and the remainder.

  • Storing a decimal value in a number with fewer decimals rounds it, commercially for a packed source; use round with a mode when a different rule is required, and round once, at the end.

  • Relational expressions compare operands; predicate expressions such as IS INITIAL, IS BOUND and line_exists( ) test one. Combine them with NOT, AND and OR, and use parentheses.

  • xsdbool( ) turns a condition into a flag value but is marked obsolete; MOVE, COMPUTE and ADD still run in classic code but are not written in new code.

Try it

To do this by hand, follow the guide Data Types, Strings and String Templates: it declares variables, converts values and builds strings and string templates.