Casting to int in awk

前端 未结 3 873
猫巷女王i
猫巷女王i 2021-01-03 22:07

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

相关标签:
3条回答
  • 2021-01-03 22:35

    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.

    0 讨论(0)
  • 2021-01-03 22:49

    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"

    0 讨论(0)
  • 2021-01-03 22:52

    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.

    0 讨论(0)
提交回复
热议问题