Casting to int in awk
Most new awks have an int() function.
But the method for casting documented in 'The Awk Programming Language' is shown as you do it, by using numericValue and +0
. I don't have the book handy, but I think you can also cast for float value by using +0.0
.
I hope this helps.
You can just use +0. say variable v
is your percentage value.
$ awk -v v="80.1%" 'BEGIN{print v+0.1}'
80.2
You do not have to get rid of the %
sign.
According to the docs, int(x)
is POSIX compliant. The number will still be a float (since all numbers in awk are floating-point) but it will be truncated to an int.
Adding 0 won't convert a string into an int. It will convert it to a float.
If you have an old awk
based on The One True AWK by Brian Kernighan, such as macOS awk
or FreeBSD awk
, you will see this at the bottom of the manpage:
BUGS
There are no explicit conversions between numbers and strings. To force
an expression to be treated as a number add 0 to it; to force it to be
treated as a string concatenate "" to it.
The scope rules for variables in functions are a botch; the syntax is
worse.
To force an expression to be treated as a number add 0 to it
If you don't care about floats and you have gawk
you can also use strtonum
Other sources:
OS X version of AWK, which is derived from "The One True AWK” by Brian Kernighan
All numbers in awk
are floating-point:
Search "All arithmetic shall follow the semantics of floating-point arithmetic as specified by the ISO C standard"
Search "all numbers in awk are floating"