psh-fractional/addition/add
Mia T. Rain 655ab2c2eb
get addition fully working !
uses 2 deep while loop instead of trying parse leading/trailing zeros like I did in psh-float; the idea is the learn from the mistakes of psh-float and try again, this is far better, but I wish less variables were used
2022-02-11 02:55:06 -05:00

25 lines
911 B
Bash
Executable file

#!/bin/sh
# add $2 to $1 and return
[ -z "${1##*.*}" -o -z "${2##*.*}" ] && { # if float # dylanaraps/pure-sh-bible#check-if-a-number-is-a-float
# modified to check $1 & $2
f1="${1##*.}"; f2="${2##*.}" # whole is ${1%.$f1} # dot required
# eq is $1+$2 -- $f1 + $f2 -- then add $1 & $2
wo="$((${1%.$f1}+${2%.$f2}))" # whole digit, this is preset and not redeclared
# this is because we may need to carry
while [ "$f1" ]; do
while [ "$f2" ]; do
next2="${f2#?}"; next1="${f1#?}"
[ "$((${f1%$next1} + ${f2%$next2}))" -gt 9 ] && {
oo="$o"; [ "$o" ] && {
: $((oo+=1))
} || : $((wo+=1))
o="$((${f1%$next1} + ${f2%$next2}))"; o="${o#?}"; o="$oo$o"; unset oo # unset to save ram
} || o="$o$((${f1%$next1} + ${f2%$next2}))"
f2="$next2"; f1="${next1}"
done
done
echo "$wo.${o:-0}"
} || { # if not just do basic addition
echo $(($1+$2))
}