Go to the first, previous, next, last section, table of contents.
Through most of this manual, we present awk values (such as constants,
fields, or variables) as either numbers or strings. This is
a convenient way to think about them, since typically they are used in only
one way, or the other.
In truth though, awk values can be both string and
numeric, at the same time. Internally, awk represents values
with a string, a (floating point) number, and an indication that one,
the other, or both representations of the value are valid.
Keeping track of both kinds of values is important for execution efficiency: a variable can acquire a string value the first time it is used as a string, and then that string value can be used until the variable is assigned a new value. Thus, if a variable with only a numeric value is used in several concatenations in a row, it only has to be given a string representation once. The numeric value remains valid, so that no conversion back to a number is necessary if the variable is later used in an arithmetic expression.
Tracking both kinds of values is also important for precise numerical calculations. Consider the following:
a = 123.321 CONVFMT = "%3.1f" b = a " is a number" c = a + 1.654
The variable a receives a string value in the concatenation and
assignment to b. The string value of a is "123.3".
If the numeric value was lost when it was converted to a string, then the
numeric use of a in the last statement would lose information.
c would be assigned the value 124.954 instead of 124.975.
Such errors accumulate rapidly, and very adversely affect numeric
computations.
Once a numeric value acquires a corresponding string value, it stays valid
until a new assignment is made. If CONVFMT
(see section Conversion of Strings and Numbers) changes in the
meantime, the old string value will still be used. For example:
BEGIN {
CONVFMT = "%2.2f"
a = 123.456
b = a "" # force `a' to have string value too
printf "a = %s\n", a
CONVFMT = "%.6g"
printf "a = %s\n", a
a += 0 # make `a' numeric only again
printf "a = %s\n", a # use `a' as string
}
This program prints `a = 123.46' twice, and then prints `a = 123.456'.
See section Conversion of Strings and Numbers, for the rules that specify how string values are made from numeric values.
Go to the first, previous, next, last section, table of contents.