bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to test whether a string is a valid number?


From: Andrew J. Schorr
Subject: Re: How to test whether a string is a valid number?
Date: Mon, 7 Sep 2020 22:38:16 -0400
User-agent: Mutt/1.5.21 (2010-09-15)

On Mon, Sep 07, 2020 at 07:00:42PM -0500, Peng Yu wrote:
> I want to know whether a string is a valid number. But it seems typeof
> is not appropriate for it? Is there something available in awk that
> can tell whether a string is a valid number? Thanks.
> 
> $ awk -v x=5 -e  'BEGIN { print typeof(3.5),typeof(x) }'
> number strnum

Typically, one tests the expression (x+0 == x),
but that works only for user input. To be safe:

function isnumeric(x,   f) {
   return (split(x, f, " ") == 1) && (f[1]+0 == f[1])
}

Or if you feel that white-space padding renders it
non-numeric, you could say:

function isnumeric(x,   f) {
   return (split(x, f, " ") == 1) && (length(f[1]) == length(x)) && (f[1]+0 == 
f[1])
}

Regards,
Andy



reply via email to

[Prev in Thread] Current Thread [Next in Thread]