I didn't see anything when searching the forums for this; maybe someone could look at this for me.
I'm trying to write a script that will take a number like 140045650.39 and turn it into $140,045,650.39
I have this icky looking thing here below, but it seems to work... I say seems because I have thrown it a few different numbers that earlier variations of the script would miscalculate (like having the number 0 as the first number in the third comma-delimited field).
This may be very horrible, but I've confused myself enough with the so-called logic of this that I can't even tell anymore. Thus, I post it:
#!/usr/bin/ksh
raw=$1
typeset -Z2 cents=${raw##*.}
money=${raw%%.*}
typeset -Z3 dol1=$money
typeset -Z6 tho2=$money
typeset -Z9 mil2=$money
typeset -L3 tho1=$tho2
typeset -L3 mil1=$mil2
typeset -L mil=${mil1##0*(0)}
[[ -z "$mil" ]] && tho=${tho1##0*(0)} || tho=$tho1
[[ -z "$tho" ]] && dol=${dol1##0*(0)} || dol=$dol1
print -n "\$"
[[ -n $mil ]] && print -n "${mil},"
[[ -n $tho ]] && print -n "${tho},"
[[ -n $dol ]] && print -n "${dol}."
print "$cents"
I know the number will never go over 999,999,999.99, and if it does, we will have problems far outweighing this script (with other processes). Does this make sense / work? Is this longer than it needs to be? It just looks like I used typeset too much
(NOTE: I do want to keep it in ksh (not perl or awk, even if it's better for this case) since that's somewhat our company scripting standard)