|
|
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 += $3pop 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 ":" $2In an ambiguous context like the following, the type of the comparison depends on whether the fields are numeric or string:
$1 == $2This 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:
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:
$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.14159To 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.1415926535See printf(S) for details of the format string syntax.