manpagez: man pages & more
info gawk
Home | html | info | man

File: gawk.info,  Node: Isnumeric Function,  Prev: Shell Quoting,  Up: General Functions

10.2.10 Checking Whether A Value Is Numeric
-------------------------------------------

A frequent programming question is how to ascertain whether a value is
numeric.  This can be solved by using this example function
'isnumeric()', which employs the trick of converting a string value to
user input by using the 'split()' function:

     # isnumeric --- check whether a value is numeric

     function isnumeric(x,  f)
     {
         switch (typeof(x)) {
         case "strnum":
         case "number":
             return 1
         case "string":
             return (split(x, f, " ") == 1) && (typeof(f[1]) == "strnum")
         default:
             return 0
         }
     }

   Please note that leading or trailing white space is disregarded in
deciding whether a value is numeric or not, so if it matters to you, you
may want to add an additional check for that.

   Traditionally, it has been recommended to check for numeric values
using the test 'x+0 == x'.  This function is superior in two ways: it
will not report that unassigned variables contain numeric values; and it
recognizes string values with numeric contents where 'CONVFMT' does not
yield the original string.  On the other hand, it uses the 'typeof()'
function (*note Type Functions::), which is specific to 'gawk'.

© manpagez.com 2000-2025
Individual documents may contain additional copyright information.