How to convert alphanumeric to numeric in Cobol?

by princess.fritsch , in category: Other , 2 years ago

How to convert alphanumeric to numeric in Cobol?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by karelle_heathcote , a year ago

@princess.fritsch In COBOL, you can use the NUMVAL function to convert an alphanumeric value to a numeric value. The NUMVAL function takes a string as an argument and returns the numeric equivalent of the string. If the string cannot be converted to a numeric value, the function returns a value of zero.


Here is an example of how you can use the NUMVAL function in COBOL:

1
2
3
4
5
   01  Alphanumeric-Value      PIC X(5).
   01  Numeric-Value           PIC S9(4) COMP.

   MOVE "12345" TO Alphanumeric-Value.
   MOVE NUMVAL(Alphanumeric-Value) TO Numeric-Value.


In this example, the value "12345" is stored in the alphanumeric field Alphanumeric-Value. The NUMVAL function is then used to convert the value in Alphanumeric-Value to a numeric value and store it in the numeric field Numeric-Value.


It's important to note that the NUMVAL function only works for strings that contain numeric characters. If the string contains any non-numeric characters, the function will return a value of zero.

Member

by wyman , 9 months ago

@princess.fritsch 

To convert an alphanumeric value to numeric in COBOL, you can use the NUMVAL or FUNCTION NUMVAL statement. Here's an example of how to use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
IDENTIFICATION DIVISION.
PROGRAM-ID. ALPHANUM-TO-NUMERIC.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 ALPHANUMERIC-VALUE PIC X(10) VALUE '12345A6789'.
01 NUMERIC-VALUE PIC 9(5).
PROCEDURE DIVISION.
MAIN-LOGIC.
    MOVE ALPHANUMERIC-VALUE TO FUNCTION NUMVAL(ALPHANUMERIC-VALUE)
    MOVE ALPHANUMERIC-VALUE TO NUMERIC-VALUE
    DISPLAY "Alphanumeric value: " ALPHANUMERIC-VALUE
    DISPLAY "Numeric value using FUNCTION NUMVAL: " ALPHANUMERIC-VALUE
    DISPLAY "Numeric value using MOVE: " NUMERIC-VALUE
    STOP RUN.


In the above example, the ALPHANUMERIC-VALUE variable holds the alphanumeric value you want to convert. The FUNCTION NUMVAL statement converts the alphanumeric value to a numeric value. You can then move the converted value to a numeric variable (NUMERIC-VALUE in this example) using the MOVE statement.


The output of the above program would be:

1
2
3
Alphanumeric value: 12345A6789
Numeric value using FUNCTION NUMVAL: 12345
Numeric value using MOVE: 12345


Note: If the alphanumeric value contains non-numeric characters, NUMVAL will only convert the leading numeric characters and ignore the rest. In the example above, NUMVAL converts '12345' and ignores 'A6789'.