004#美化多位数字

将给定的数字以逗号分隔的形式显示出来

代码:

#!/bin/bash
# FILENAME: nicenum.sh
# 可接受两个选项:DD(decimal pointa,小数分隔符)
# 和TD(thousands delimiter,千位分隔符)
#

niceNumber()
{
  # 检测输入数字的小数分隔符是否与用户请求的相同
  sep="$(echo $1 | sed 's/[[:digit:]]//g')"
  echo $sep
  if [ ! -z "$sep" -a "$sep" != "$DD" ]; then
    echo "$0: Unknown decimal separator $sep encountered." >&2
    exit 1
  fi
  # 默认以"."为小数分隔符
  # 可通过-d指定其他小数分隔符
  # 取出整数部分,即小数分隔符左侧数字
  int=$(echo $1 | cut "-d$DD" -f1)
  # 取出小数部分
  decimal=$(echo $1 | cut "-d$DD" -f2)
  # 检查输入数字是否包含小数,有则保存
  if [ "$decimal" != "$1" ]; then
  # 保存小数到result
    result="${DD:='.'}$decimal"
  fi
  thousands=$int
  while [ $thousands -gt 999 ]; do
    # 对整数进行求余,以判断3个最低有效数字
    remainder=$(($thousands%1000))
    while [ ${#remainder} -lt 3 ]; do
      # 加入前导数字0
      remainder="0$remainder"
    done
    # 从右到左构建最终结果
    result="${TD:=','}${remainder}$result"
    # 对1000求商,移除3个最低有效数字
    thousands=$((thousands/1000))
  done
  nicenum="${thousands}${result}"
  if [ ! -z $2 ]; then
    echo $nicenum
  fi
}
  DD="."
  TD=","

  # main
  # 解析传入参数 d,t
  while getopts "d:t:" opt; do
    case $opt in
      d) DD="$OPTARG" ;; 
      t) TD="$OPTARG" ;;
    esac
  done
  shift $(($OPTIND - 1))
  if [ $# -eq 0 ]; then
    echo "Usage: $(basename $0) [-d c] [-t c] numeric_value"
    echo " -d specifies the decimal point delimiter (default '.')"
    echo " -t specifies the thousands delimiter (default ',')"
    exit 0
  fi
  # 第二个参数强制nicenumber函数回显输出
  niceNumber $1 1
  exit 0

猜你喜欢

转载自www.cnblogs.com/bigtree2pingping/p/12938373.html
今日推荐