I'm looking for a method to cast a string to an int in awk. I have the following which appears to be doing a string comparison
(note: field $5
is a percentage in one of two formats: 80%
or 9.0%
)
awk '{if (substr($5,1,(length($5)-1)) >= 90) ...
So, when I change it to:
awk '{if (substr($5,1,(length($5)-1))+0 >= 90+0 ) ...
It compares as I intended. Is this an appropriate cast? Is there a 'better' way to perform the cast?
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 "25fix" has a numeric value of 25.
According to the GNU awk manual, The way printf and sprintf() (see Printf) perform rounding often depends upon the system's C sprintf() subroutine. On many machines, sprintf() rounding is “unbiased,” which means it doesn't always round a trailing '.
To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.
AWK has lots of built-in functions for numeric, string, input, and output operations. Awk has the following two types of high level built-in function categories: Built-in functions for numeric operations. Built-in functions for string operations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With