psh-fractional/subtraction/sub

62 lines
1.5 KiB
Bash
Executable file

#!/bin/sh
rad(){ # add decimal to $1 based on $2
# literal reverse of what ad() from multiplication/mul does
m="$1"; n=0; while [ "$m" ]; do
next="${m#?}"
[ "$n" -eq "$2" ] && break
e="${e}${m%$next}"
m="$next"; : $((n+=1))
done
w="${1#$e}"; echo "${3}${e}.${w:-0}"
}
fd() {
m="$1"; n=1; while [ "$m" ]; do
next="${m%?}"
[ "$n" -eq "${#1}" ] && {
echo "${m%next}"
break
}
: $((n+=1)); m="$next"
done
}
[ -z "${1##*.*}" -o -z "${2##*.*}" ] || { # if not floats
echo "$(($1-$2))"
exit 0
}
if [ ! -z "${1##*.*}" ]; then
set -- "${1}.0" "$2"; d="${1#*.}"; d2="${2#*.}"
until [ "${#d}" -eq "${#d2}" ]; do
set -- "${1}0" "$2"
d="${1#*.}"
done
elif [ ! -z "${2##*.*}" ]; then
set -- "$1" "${2}.0"; d="${2#*.}"; d2="${1#*.}"
until [ "${#d}" -eq "${#d2}" ]; do
set -- "$1" "${2}0"
d="${2#*.}"
done
fi # if $1/$2 is not a float; convert to float
m1="${1%.*}"; m2="${2%.*}"; if [ "${#m2}" -gt "${#m1}" ]; then
dn="${#m2}"
elif [ "${#m2}" -eq "${#m1}" ]; then
dn="${#m1}"
else
dn="${#m1}"; : $((dn+=1))
fi
## SWAP IF $1 > $2; negative handling
m1="${1%.*}${1#*.}"; m2="${2%.*}${2#*.}"
[ "$m1" -lt "$m2" ] && {
set -- "$2" "$1"
m1="${1%.*}${1#*.}"; m2="${2%.*}${2#*.}"; nr="-"
}
#echo "$m1 $m2 $dn"
until [ "${m1#0}" = "$m1" ]; do
m1="${m1#0}"
done
until [ "${m2#0}" = "$m2" ]; do
m2="${m2#0}"
done # dash has issues when numbers have leading 0's
# zsh,bash,etc don't need this at all
# and really dash shouldn't either but /shrug
rad "$((m1-m2))" "$dn" "${nr}"