値の大きな数を見やすくする(,を入れる)

#!/bin/sh
#nicenamber.sh

nicenumber(){
    #入力された値は.を小数点の区切り文字と見なして処理する
    #-dフラグで別の値を指定された場合を除き、出力される値の小数点の
    #区切り文字には.が使われる

    #小数点の左側を取り出す
    integer=$(echo $1 | cut -d. -f1)
    #小数点の右側を取り出す
    decimal=$(echo $1 | cut -d. -f2)

    if [ $decimal != $1 ]; then
        #小数点以下の部分があれば取り込む
        result="${DD:="."}$decimal"
    fi

    thousands=$integer

    while [ $thousands -gt 999 ]; do 
        remainder=$(($thousands % 1000))    #下3桁の数字

        while [ ${#remainder} -lt 3 ]; do 
            remainder="0$remainder"         #必要に応じて先行する0を付加
        done

        thousands=$(($thousands / 1000))    #次の桁の処理
        result="${TD:=","}${remainder}${result}" #右から左に文字列を連結
    done

    nicenum="${thousands}${result}"
    if [ ! -z $2 ]; then
        echo $nicenum
    fi
}

DD="."  #小数点の区切り文字
TD=","  #桁の区切り文字

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 $1 1
exit 0
$ ./nicenumber.sh 5894625
5,894,625

$ ./nicenumber.sh 5894625.433
5,894,625.433

$ ./nicenumber.sh -d, -t. 5894625.433
5.894.625,433