Wednesday, 17 October 2007

ABAP: How to tell if user input is a number

ABAP casts between types by just sequentially copying (as many as the size of the target type) bytes from one memory area to an other and then checks if the new contents of the target memory area can be perceived as the appropriate type. As a general rule strings and character objects are always copied left while numbers get copied right justified)

This little code fragment will get a number out of a string and convert it to practically any numeric format.

        DATA :
           temp_str(10) type c value '1234,34'.
           my_number TYPE f.

*       If the value of temp_str is comming from user input of from any other
*       user or ABAP dictionary type then it is also wise to execute something like
        CONDENSE temp_str.

*       You may want to execute this if you --like me -- your 
*       decimal symbol is a comma
        REPLACE ',' WITH '.' INTO temp_str.

        CATCH SYSTEM-EXCEPTIONS conversion_errors = 4.
          my_number = temp_str.
        IF sy-subrc <> 0.
          MESSAGE e888(sabapdocu) WITH temp_str ' is not a number'.

No comments :