Home > Mobile >  How to search numbers after decimal point for floating point number in Bash?
How to search numbers after decimal point for floating point number in Bash?

Time:12-19

I am messing around with something on bash (I am very new to it).

I have a floating point number.

I want to to be able to check if there is any digits after the decimal point from 1-9 in order to determine whether it is a whole number - and do it within an if-else statement.

for example

if(*number does have a 1-9 digit after decimal*)
then
    echo 'Number is not a whole number'
else
    echo 'Number is a whole number'
fi

Dabbled with grep and REGEX but don't have a great grasp of it yet

CodePudding user response:

Mac_3.2.57$cat findWhole.bash
#!/bin/bash
for x in 1.123456789 0001230045600.00 1.000000 1 1. 1.. 0002 .00 22.00023400056712300 1.00 .
do
  if [[ "$x" =~ ^[0-9]*\.[0-9]*[1-9][1-9]*[0-9]*$ ]]; then
    echo "$x is not a whole number"
  elif [[ "$x" =~ ^[0-9][0-9]*\.?0*$|^\.00*$ ]]; then
    echo "$x is a whole number"
  else
    echo "$x is not a number"
  fi
done
Mac_3.2.57$./findWhole.bash
1.123456789 is not a whole number
0001230045600.00 is a whole number
1.000000 is a whole number
1 is a whole number
1. is a whole number
1.. is not a number
0002 is a whole number
.00 is a whole number
22.00023400056712300 is not a whole number
1.00 is a whole number
. is not a number
Mac_3.2.57$

CodePudding user response:

With a regex:

x=1.123456789
if [[ "$x" =~ \.[0-9]{1,9}$ ]]; then
  echo 'Number is not a whole number'
else
  echo 'Number is a whole number'
fi

Output:

Number is not a whole number
  • Related