Money script


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Money script
# 1  
Old 03-27-2002
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:
Code:
#!/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 Smilie

(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)
# 2  
Old 03-27-2002
Well I would use sed...
Code:
#! /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

# 3  
Old 03-27-2002
Well shoot, there went a good chunk of time down the drain Smilie

Thank you, though - I'm going to try to work some of that into the big picture!
Login or Register to Ask a Question

Previous Thread | Next Thread

1 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Format Money/Currency (U.S.)

I have looked everywhere. Does bash have a money/currency format for output? Do I have to use awk or printf? Thank you (4 Replies)
Discussion started by: Ccccc
4 Replies
Login or Register to Ask a Question