Money script

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 :stuck_out_tongue:

(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)

Well I would use sed...

#! /usr/bin/ksh
typeset -Z11 raw
raw=$1
format=$(echo $raw | sed 's/\(...\)\(...\)\(...\)\(..\)/\1,\2,\3.\4/')
format=${format##+([0,])}
[[ $format = .* ]] && format=0${format}
echo $format
exit 0

Well shoot, there went a good chunk of time down the drain :stuck_out_tongue:

Thank you, though - I'm going to try to work some of that into the big picture!