awkConverts Between Strings and Numbers
Strings are converted to numbers and numbers are converted to strings, if the context
awk program demands it. For example, if the value of
bar in the expression ‘foo + bar’
happens to be a string, it is converted to a number before the addition
is performed. If numeric values appear in string concatenation, they
are converted to strings. Consider the following:
two = 2; three = 3 print (two three) + 4
This prints the (numeric) value 27. The numeric values of
three are converted to strings and
concatenated together. The resulting string is converted back to the
number 23, to which 4 is then added.
If, for some reason, you need to force a number to be converted to a
string, concatenate that number with the empty string,
To force a string to be converted to a number, add zero to that string.
A string is converted to a number by interpreting any numeric prefix
of the string as numerals:
"2.5" converts to 2.5,
"1e3" converts to 1,000, and
has a numeric value of 25.
Strings that can’t be interpreted as valid numbers convert to zero.
The exact manner in which numbers are converted into strings is controlled
awk predefined variable
CONVFMT (see Built-in Variables).
Numbers are converted using the
CONVFMT as the format
(see String Functions).
CONVFMT’s default value is
"%.6g", which creates a value with
at most six significant digits. For some applications, you might want to
change it to specify more precision.
On most modern machines,
17 digits is usually enough to capture a floating-point number’s
Strange results can occur if you set
CONVFMT to a string that doesn’t
sprintf() how to format floating-point numbers in a useful way.
For example, if you forget the ‘%’ in the format,
all numbers to the same constant string.
As a special case, if a number is an integer, then the result of converting
it to a string is always an integer, no matter what the value of
CONVFMT may be. Given the following code fragment:
CONVFMT = "%2.2f" a = 12 b = a ""
b has the value
Prior to the POSIX standard,
Pathological cases can require up to 752 digits (!), but we doubt that you need to worry about this.