DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Using awk

Number or string?

Variables, fields, and expressions can have a numeric value, a string value, or both at any time. They take on numeric or string values according to context. For example, in the context of an arithmetic expression like the following:

   pop += $3
pop and $3 must be treated numerically, so it must be ensured that their values are of the numeric type when arithmetic operations are performed on them. This is often called type coercion.

Similarly, in the following string, $1 and $2 must be strings, so they can be type coerced if concatenation operations are to be performed.

   print $1 ":" $2
In an ambiguous context like the following, the type of the comparison depends on whether the fields are numeric or string:
   $1 == $2
This can only be determined when the program runs; it might differ from record to record. For example, the above comparison succeeds on any pair of the following inputs:

1 1.0 +1 0.1e+1 10E-1 001

However, it fails on the following inputs:

(null) 0
(null) 0.0
0a 0
1e50 1.0e50

In comparisons, if both operands are numeric, the comparison is numeric; otherwise, operands are coerced to strings, and the comparison is made on the string values. The determination of type is done at run time.

There are two idioms for coercing an expression of one type to the other:


number ``''
concatenate a null string to a number to coerce it to type string

string + 0
add zero to a string to coerce it to type numeric
Thus, the following forces a string comparison between two fields:
   $1 "" == $2 ""
The numeric value of a string is the value of any prefix of the string that looks numeric; thus the value of 12.34x is 12.34, while the value of x12.34 is zero. The string value of an arithmetic expression is computed by formatting the string with the output format conversion OFMT. OFMT specifies a printf-style format. By default, OFMT is %.6g (truncate argument to six digits). For example:
   {pi=3.1415926535; print pi}
This prints the following:
   3.14159
To print pi to 10 significant digits, use the format specifier "%.10f", as follows:
   BEGIN {OFMT="%.10f"}
           {pi=3.1415926535; print pi}
This program outputs the following:
   3.1415926535
See printf(S) for details of the format string syntax.

Next topic: A handful of useful one-liners
Previous topic: User-defined variables

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003