[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: How to test whether a string is a valid number?
From: |
david kerns |
Subject: |
Re: How to test whether a string is a valid number? |
Date: |
Mon, 7 Sep 2020 19:21:48 -0700 |
This is the elegance that is awk ... everything is a string AND everything
is a number.
gawk 'BEGIN { a="3";b=3; print typeof(a + 0), typeof(a " "), typeof(b + 0),
typeof(b " ") }'
number string number string
if you need to determine for a random value, you need to regex match for a
number or the trivial case where you coerce to a number, then back to a
string and see if if matches original value.
$ gawk '
function nors(a) {
if (((a + 0) "") == a || a ~ /^[-+]?[0-9]+(\.[0-9]*)?(e[-+]?[0-9]+)?$/ ||
a ~ /^[-+]?[0-9]*(\.[0-9]+)(e[-+]?[0-9]+)?$/)
print a, "number";
else
print a, "string";
}
BEGIN {
v = .0; nors(v);
v = 0.; nors(v);
v = 0.0; nors(v);
v = -0.0; nors(v);
v = +0.0; nors(v);
v = 0; nors(v);
v = ".0"; nors(v);
v = "0."; nors(v);
v = "0.0"; nors(v);
v = "-0.0"; nors(v);
v = "+0.0"; nors(v);
v = "0"; nors(v);
v = "fred"; nors(v);
v = "123abc"; nors(v);
v = "123"; nors(v);
v = "0.00000000001"; nors(v);
v = ".1e4"; nors(v);
v = "."; nors(v);
v = ".e"; nors(v);
}'
0 number
0 number
0 number
0 number
0 number
0 number
.0 number
0. number
0.0 number
-0.0 number
+0.0 number
0 number
fred string
123abc string
123 number
0.00000000001 number
.1e4 number
. string
.e string
On Mon, Sep 7, 2020 at 5:00 PM Peng Yu <pengyu.ut@gmail.com> wrote:
> Hi,
>
> 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
>
> --
> Regards,
> Peng
>
>