Previous: , Up: General Programming   [Contents][Index]

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")
        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 (see Getting Type Information), which is specific to gawk.