SHELL/BASH:在Linux中给数字添加千位分隔符

时间:2020-02-23 14:37:37  来源:igfitidea点击:

在本文中,我将共享一个示例脚本,以"在数字中添加千位分隔符逗号"(可以是十进制或者完整整数)。程序员经常犯的一个错误是不先格式化就将计算结果呈现给用户。对于用户来说,很难确定是否有成千上万的43245435,而不是从右到左进行计数,并且很难每三位数插入一个逗号。因此,逗号将用于添加数千个分隔符。

添加千位分隔符的脚本

下面是一个示例脚本,可用于在数字中添加数千个分隔符。我们可以根据需要修改脚本。

[root@node1 ~]# cat /tmp/nicenumber.sh
   #!/bin/bash
   # nicenumber--Given a number, shows it in comma-separated form. Expects DD
   #   (decimal point delimiter) and TD (thousands delimiter) to be instantiated.
   #   Instantiates nicenum or, if a second arg is specified, the output is
   #   echoed to stdout.
   nicenumber()
   {
      # Note that we assume that '.' is the decimal separator in the INPUT value
      # to this script. The decimal separator in the output value is '.'
     integer=$(echo  | cut -d. -f1)        # Left of the decimal
     decimal=$(echo  | cut -d. -f2)        # Right of the decimal
     
     # Check if number has more than the integer part.
     if [ "$decimal" != "" ]; then
        # There's a fractional part, so let's include it.
        result="${DD:= '.'}$decimal"
     fi
     thousands=$integer
     while [ $thousands -gt 999 ]; do
          remainder=$(($thousands % 1000))    # Three least significant digits
          # We need 'remainder' to be three digits. Do we need to add zeros?
          while [ ${#remainder} -lt 3 ] ; do  # Force leading zeros
              remainder="0$remainder"
          done
          result="${TD:=","}${remainder}${result}"    # Builds right to left
          thousands=$(($thousands/1000))    # To left of remainder, if any
     done
     nicenum="${thousands}${result}"
     if [ ! -z  ] ; then
        echo $nicenum
     fi
   }
   DD="."  # Decimal point delimiter, to separate whole and fractional values
   TD=","  # Add thousands separator using (,) to separate every three digits
   # Input validation
   if [ $# -eq 0 ] ; then
     echo "Please provide an integer value"
     exit 0
   fi
   # BEGIN MAIN SCRIPT
   # =================
   nicenumber  1   # Second arg forces nicenumber to 'echo' output.
   exit 0

脚本如何工作?

该脚本的核心是nicenumber()函数中的while循环,该循环不断从存储在变量数千中的数字值中删除三个最低有效数字,并将这些数字添加到要构建的数字的漂亮版本向上。然后,循环将减少成千上万个存储的数量,并在必要时再次将其通过循环。一旦完成了" nicenumber()"功能,主脚本逻辑就会启动。首先,它使用getopts解析传递给脚本的所有选项,最后使用用户指定的最后一个参数调用nicenumber()函数。

运行脚本

其中我使用两个示例执行了脚本,以将数千个分隔符添加到所提供的整数和十进制值中。

[root@node1 ~]# /tmp/nicenumber.sh 123456789
123,456,789
[root@node1 ~]# /tmp/nicenumber.sh 1234567890
1,234,567,890
[root@node1 ~]# /tmp/nicenumber.sh 1234567890.456
1,234,567,890.456