006#验证浮点数输入

基本思路:

1、检查输入值是否包含小数点"."

2、包含小数点则对小数点的整数部分和小数部分分开测试

3、确保小数点两边都是有效的整数,且没有多余的负号(针对validint进行补充判断)

4、最后检查是否输入值只是一个负号和小数点

5、其他:待增强

注:本脚本不接受科学计数法:1.24e4

#!/usr/bin/env bash
#
# FILENAME: validfloat.sh
# 验证浮点数输入
#
# 整数判断
validint(){
  number=$1
  min=$2
  max=$3

  # 空值检测
  if [ -z $number ]; then
    echo "You didn't input anything." >&2
    return 1
  fi

  # 负数符号检测
  if [ "${number%${number#?}}" = "-" ]; then
    num="${number#?}"
  else
    num="${number}"
  fi
  
  # 检查除负数符号后的数字是否是整数
  nodigits=$(echo $num | sed 's/[[:digit:]]//g')
  if [ ! -z "$nodigits" ]; then
    echo "Invalid number format. Only digits, no commas, spaces, etc." >&2
    return 1
  fi

  # 判断输入值是否小于指定最小值
  if [ ! -z $min ]; then
    if [ $number -lt $min  ]; then
      echo "You value is too small. the smallest value is $min" >&2
      return 1
    fi
  fi

  # 判断输入值是否大于指定最大值
  if [ ! -z $max ]; then
    if [ $number -gt $max ]; then
      echo "You value is too big. the largest value is $max" >&2
      return 1
    fi
  fi

  return 0
}

# 浮点数判断
validfloat(){
  fvalue="$1"
  # 检查输入的数字是否有小数点
  if [ ! -z $(echo $fvalue|sed 's/[^.]//g') ]; then
    integerPart="$(echo $fvalue|cut -d. -f1)" # 整数部分
    decimalPart="${fvalue#*.}"  # 小数部分
    
    # 判断整数部分是否合法
    if [ ! -z $integerPart ]; then
      if ! validint "$integerPart" "" ""; then
        return 1
      fi
    fi

    # 判断小数部分是否合法
    if [ "${decimalPart%${decimalPart#?}}" = "-" ]; then
      echo "Invalid float number: '-' not allowed after decimal point." >&2
      return 1
    fi

    if [ "${decimalPart}" != "" ]; then
      if ! validint "$decimalPart" "0" ""; then
        return 1
      fi
    fi
  else
    if [ "$fvalue" = "-" ]; then
      echo "Invalid float format. " >&2
      return 1
    fi
  
    if ! validint "$fvalue" "" ""; then
      return 1
    else
      echo "$1 is integer number."
      return 1
    fi
  fi
    return 0
}

# 验证浮点数输入
if [ $# -ne 1 ]; then 
  echo "Usage: $0 floating_Number." >&2
  exit 1
fi

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

 

posted @ 2020-05-25 15:06  bigtree2pingping  阅读(183)  评论(0编辑  收藏  举报