[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:44:19 -0400 |
User-agent: |
Mutt/1.5.21 (2010-09-15) |
On Mon, Sep 07, 2020 at 10:38:16PM -0400, Andrew J. Schorr wrote:
> 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])
> }
Or maybe this might be more efficient:
function isnumeric(x, f) {
switch (typeof(x)) {
case "number":
case "strnum":
return 1
case "string":
return (split(x, f, " ") == 1) && (length(f[1]) == length(x)) && (f[1]+0
== f[1])
default:
return 0
}
}
But the strnum type ignores leading & trailing whitespace, so you may want
to use the string test for that case also.
Regards,
Andy