|
| 1 | +#!/bin/sh |
| 2 | + |
| 3 | +# nicenumber - given a number, show it with comma separated values |
| 4 | +# expects DD and TD to be instantiated. instantiates nicenum |
| 5 | +# or, if a second arg is specified, the output is echoed to stdout |
| 6 | + |
| 7 | +nicenumber() |
| 8 | +{ |
| 9 | + # Note that we use the '.' as the decimal separator for parsing |
| 10 | + # the INPUT value to this script. The output value is as specified |
| 11 | + # by the user with the -d flag, if different from a '.' |
| 12 | + |
| 13 | + integer=$(echo $1 | cut -d. -f1) # left of the decimal |
| 14 | + decimal=$(echo $1 | cut -d. -f2) # right of the decimal |
| 15 | + |
| 16 | + if [ $decimal != $1 ]; then |
| 17 | + # there's a fractional part, let's include it. |
| 18 | + result="${DD:="."}$decimal" |
| 19 | + fi |
| 20 | + |
| 21 | + thousands=$integer |
| 22 | + |
| 23 | + while [ $thousands -gt 999 ]; do |
| 24 | + remainder=$(($thousands % 1000)) # three least significant digits |
| 25 | + |
| 26 | + while [ ${#remainder} -lt 3 ] ; do # force leading zeroes as needed |
| 27 | + remainder="0$remainder" |
| 28 | + done |
| 29 | + |
| 30 | + thousands=$(($thousands / 1000)) # to left of remainder, if any |
| 31 | + result="${TD:=","}${remainder}${result}" # builds right-to-left |
| 32 | + done |
| 33 | + |
| 34 | + nicenum="${thousands}${result}" |
| 35 | + if [ ! -z $2 ] ; then |
| 36 | + echo $nicenum |
| 37 | + fi |
| 38 | +} |
| 39 | + |
| 40 | +DD="." # decimal point delimiter, between integer & fractional value |
| 41 | +TD="," # thousands delimiter, separates every three digits |
| 42 | + |
| 43 | +while getopts "d:t:" opt; do |
| 44 | + case $opt in |
| 45 | + d ) DD="$OPTARG" ;; |
| 46 | + t ) TD="$OPTARG" ;; |
| 47 | + esac |
| 48 | +done |
| 49 | + |
| 50 | +shift $(($OPTIND - 1)) |
| 51 | + |
| 52 | +if [ $# -eq 0 ] ; then |
| 53 | + cat << "EOF" >&2 |
| 54 | +Usage: $(basename $0) [-d c] [-t c] numeric value |
| 55 | + -d specifies the decimal point delimiter (default '.') |
| 56 | + -t specifies the thousands delimiter (default ',') |
| 57 | +EOF |
| 58 | + exit 1 |
| 59 | +fi |
| 60 | + |
| 61 | +nicenumber $1 1 # second arg forces this to 'echo' output |
| 62 | + |
| 63 | +exit 0 |
0 commit comments