awk printf formatting using string format specifier.

Hi all,

My simple AWK code does

C = A - B

If C can be a negative number, how awk printf formating handles it using string format specifier.

Thanks in advance
Kanu
:confused:

%d would be the normal one to use for whole integers.

awk 'BEGIN { printf("%d\n",C) }'

My code:

#!/bin/awk -f
BEGIN {

# Enter the numbers
        a = 2;
        b = 3;
        c = a - b;

                printf ("The first number is%d\n",a);
                printf ("The second number is%d\n",b);
                printf ("The result is%d\n",c);


exit;
}

result:

The first number is2
The second number is3
The result is-1

i want there the whole number using format specifier...:frowning:

means value of C should come around to be 1 (absolute value)

If you want the absolute value of the number you want to print,
why don't you store it as an absolute value in the first place,
i.e., c = abs (a - b)
note that you should include the external library stdlib.h for using this function with integer values.
when you printf c you'll get a nonsigned number
else you can incorporate abs in the printf command

printf ("The result is %d\n", abs(c))

something like that

OK! thanks budd! how to do it with a format specifier??

Try %u it is the unsigned integer format specifier used in C programming just like printf command.
I hope it will work with awk.

%u is not working ... giving something like 1897600 as result.

thanks again!!
and thanks in advance :slight_smile:

edited

The format specifiers are not designed to do conversions. You should follow fmina's advice and use the abs() function. The internal representation of a negative integer causes the highest bit to be set to 1, so if it is treated as an unsigned number (by using %u) it appears to be a very large positive number. Using an 8-bit number as an example, 10000000 is -128 when treated as an integer, but 128 when treated as an unsigned. 10000001 is -127 integer, 129 unsigned. 11111111 is -1 integer, 255 unsigned.