How do I check decimal numbers?
Hi i am working on an assignment and stuck at this part, how to check decimals / numbers in shell?
It can accept numbers, but not decimal numbers. I wish he could accept both.
This is what I still have
if echo $value | egrep '^[0-9]+$' >/dev/null 2>&1 ; then
echo "OK"
else
echo "There Is An Error"
echo "Please Try Again"
fi
+3
source to share
7 replies
Using bash pattern matching:
shopt -s extglob
while read line; do
if [[ $line == ?([-+])+([0-9])?(.*([0-9])) ]] ||
[[ $line == ?(?([-+])*([0-9])).+([0-9]) ]]
then
echo "$line is a number"
else
echo "$line NOT a number"
fi
done << END
1
-1
a
1a
1.0
1.
.0
.
-.0
+
+0
+.0
END
outputs
1 is a number
-1 is a number
a NOT a number
1a NOT a number
1.0 is a number
1. is a number
.0 is a number
. NOT a number
-.0 is a number
+ NOT a number
+0 is a number
+.0 is a number
Templates:
- an optional character followed by one or more digits, followed by an optional period and zero or more digits
- an optional character, followed by zero or more digits, followed by a mandatory period, followed by one or more digits.
+1
source to share
Works in both Bash 3.0 and 4.0.
isInteger() {
[[ $1 =~ ^[0-9]+$ ]];
}
isDecimal() {
[[ $1 =~ ^[0-9]+\.[0-9]+$ ]] && ! isInteger $1;
}
computer:~ # isDecimal 123 && echo true || echo false
false
computer:~ # isDecimal 12.34 && echo true || echo false
true
computer:~ # isDecimal 12.34a && echo true || echo false
false
computer:~ # isDecimal 0.0000001 && echo true || echo false
true
To check the number, just test both functions.
0
source to share