h0ujun
April 23, 2012, 5:45am
1
i have this code:
a=hello999999999999999999999999999999999999999999999999999999999
b=`echo ${a} | tr -d '[:alpha:]'`
if [ ${b} -le 0 ] ; then
echo "Zero"
fi
but when I execute this I am having this error: Numerical result out of range
Anyone know how to handle this?
Thanks!!
You could try something like:
a=hello999999999999999999999999999999999999999999999999999999999
b=`echo ${a} | awk 'gsub(/[a-zA-Z]/,x)'`
if [ "${b}" = "" ] ; then
echo "Zero"
fi
I would use something like this:
a=hello999999999999999999999999999999999999999999999999999999999
awk -v n="$a" 'BEGIN {
gsub(/[^0-9]/, x, n)
if (n == 0) print "Zero"
}'
You could easily extend the code to handle negative and floating point numbers too:
a=hello-99999999999999999999999999999999999999999999999999999999.9
awk -v n="$a" 'BEGIN {
gsub(/[^0-9.-]/, x, n)
(n ~ /-/ && n ~! /^-/) && gsub(/-/, x, n)
if (n <= 0) print "Zero"
}'
And, of course, special care should be taken to handle strings like these:
hello-9-99
h.ello9
h0ujun
April 23, 2012, 10:39pm
4
franklin52:
You could try something like:
a=hello999999999999999999999999999999999999999999999999999999999
b=`echo ${a} | awk 'gsub(/[a-zA-Z]/,x)'`
if [ "${b}" = "" ] ; then
echo "Zero"
fi
hmmm i need to compare the number so I cannot use
if [ "${b}" = "" ] ; then
Something like this?
if [ "${b}" = "" ] ; then
echo "No numbers"
elif [ "${b}" -le 0 ] ; then
echo "Less or equal to 0"
elif [ "${b}" -gt 0 ] ; then
echo "Greater then 0"
fi