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


Instead of using grep, you can use bash to test the expression:



#!/bin/bash

value=98.23
if [[ "$value" =~ ^[0-9]+(\.[0-9]+)?$ ]]
then
   echo good
else
   echo bad
fi

      

+5


source


use this regex instead ^[0-9]*(\.[0-9]+)?$



+2


source


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


How about this:

if [ ! -z $(echo "$value" | grep -o "^[1-9][0-9]*\.\?[0-9]*$") ]; then echo ok; fi

      

-z

checks for an empty string. Thus, negation [ ! -z "" ]

will be performed if the given string begins with a match pattern.

0


source


The standard shell ( [[

non-standard) test

will do the check for you.

if test "$value" -eq 0 -o "$value" -ne 0 2> /dev/null; then
  : # $value is an integer
else
  : # $value is not an integer
fi

      

0


source


Try this: it checks for negative and decimal numbers too.  

echo $value | egrep '^-[0-9]+$|^[0-9]+$|^[0-9].[0-9]+$|^-[0-9].[0-9]+$' > /dev/null

      

0


source


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







All Articles