# 验证浮点数

#!/bin/bash

#整数验证,利用match函数
validint(){
a=\$1
ret=\$(echo \$a | awk '{stat=match(\$1,"^[0-9]+\$");if(stat==0) print "1";else print "0"}')
return \$ret
}

#浮点数组成:0-9,负号(-)和点(.),其中负号,在最前面,点,只能出现一次
validfloat(){
fvalue="\$1"

#当前参数是否包含小数点,如有,将其拆分为整数和小数部分,分别判断.
if [ ! -z \$(echo \$fvalue | sed 's/[^.]//g') ];then
decimalpart=\$(echo \$fvalue | cut -d. -f1)
fractionalpart=\$(echo \$fvalue | cut -d . -f2)
#如整数部分不为空,但非法
if [ ! -z \$decimalpart ];then
if ! validint "\$decimalpart";then
echo "decimalpart is not valid integer."
return 1
fi
fi
#小数部分不为空,第1个字符"-",是非法
if [ "\${fractionalpart:0:1}" = "-" ];then
echo "Invalid floating-point number: '-' not allowed after decimal point." >&2
return 1
fi
#小数部分不为空,但小数部分不是合法integer;
if [ "\$fractionalpart" != "" ];then
if ! validint "\$fractionalpart" ;then
echo "fractionalpart is not valid integer."
return 1
fi
fi
#整数部分仅为'-',或为空,如,小数部分是空
if [ "\$decimalpart" = "-" -o -z "\$decimalpart" ];then
if [ -z \$fractionalpart ];then
echo "Invalid floating-point format." >&2
return 1
fi
fi
else
#如当前参数仅为'-'
if [ "\$fvalue" = "-" ];then
echo "Invalid floating-point format." >&2
return 1
fi
#参数中没有小数点,该值不是合法整数
if ! validint "\$fvalue" ;then
echo "Invalid floating-point format." >&2
return 1
fi

fi
return 0
}

if validfloat \$1 ; then
echo "\$1 is a valid floating-point value."
fi
exit 0

• 博文量
82
• 访问量
460821