bash_functions
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revision | Next revisionBoth sides next revision | ||
bash_functions [2014/08/05 18:49] – [Print lines on screen descending from the current point] k2patel | bash_functions [2014/09/29 01:25] – [Integer or Decimal] k2patel | ||
---|---|---|---|
Line 225: | Line 225: | ||
[[ https:// | [[ https:// | ||
+ | |||
+ | ==== floating point multiplication ==== | ||
+ | <code bash> | ||
+ | fpmul() #@ Perform floating-point multiplication in the shell | ||
+ | { #@ USAGE: fpmul [VAR] NUM.DEC ... | ||
+ | local _var= _places _tot _neg _n _int _dec _df _fpmul | ||
+ | if [[ ${1^^} =~ ^[A-Z_][A-Z0-9_]*$ ]] | ||
+ | then | ||
+ | _var=$1 | ||
+ | shift | ||
+ | fi | ||
+ | _places= | ||
+ | _tot=1 | ||
+ | _neg= | ||
+ | for _n | ||
+ | do | ||
+ | ## 2 negatives make a positive | ||
+ | case $_n in | ||
+ | -*) [ " | ||
+ | _n=${_n#-} | ||
+ | ;; | ||
+ | esac | ||
+ | |||
+ | ## Check for non-numeric characters | ||
+ | case $_n in | ||
+ | *[!0-9.]*) return 1 ;; | ||
+ | esac | ||
+ | |||
+ | ## count the number of decimal _places, | ||
+ | ## then remove the decimal point | ||
+ | case $_n in | ||
+ | .*) _int= | ||
+ | _dec=${_n#? | ||
+ | _places=$_places$_dec | ||
+ | _n=$_dec | ||
+ | ;; | ||
+ | *.*) _dec=${_n# | ||
+ | _int=${_n%.*} | ||
+ | _places=$_places$_dec | ||
+ | _n=$_int$_dec | ||
+ | ;; | ||
+ | esac | ||
+ | |||
+ | ## remove leading zeroes | ||
+ | while : | ||
+ | do | ||
+ | case $_n in | ||
+ | "" | ||
+ | _fpmul=0 | ||
+ | return | ||
+ | ;; | ||
+ | 0*) _n=${_n#0} ;; | ||
+ | *) break;; | ||
+ | esac | ||
+ | done | ||
+ | |||
+ | ## multiply by the previous _total | ||
+ | _tot=$(( $_tot * ${_n:-0} )) | ||
+ | |||
+ | ## report any overflow error | ||
+ | case $_tot in | ||
+ | -*) printf " | ||
+ | return 1 | ||
+ | ;; | ||
+ | esac | ||
+ | done | ||
+ | |||
+ | while [ ${#_tot} -lt ${#_places} ] | ||
+ | do | ||
+ | _tot=0$_tot | ||
+ | done | ||
+ | |||
+ | _df= | ||
+ | while [ ${#_df} -lt ${#_places} ] | ||
+ | do | ||
+ | left=${_tot%? | ||
+ | _df=${_tot# | ||
+ | _tot=$left | ||
+ | done | ||
+ | _fpmul=$_tot${_df: | ||
+ | |||
+ | ## remove trailing zeroes or decimal points | ||
+ | while : | ||
+ | do | ||
+ | case $_fpmul in | ||
+ | *.*[0\ ]|*.) _fpmul=${_fpmul%? | ||
+ | .*) _fpmul=0$_fpmul ;; | ||
+ | *) break ;; | ||
+ | esac | ||
+ | done | ||
+ | |||
+ | [[ $_var ]] && | ||
+ | printf -v " | ||
+ | printf ' | ||
+ | } | ||
+ | num.dec | ||
+ | </ | ||
+ | |||
+ | [[http:// |
bash_functions.txt · Last modified: 2020/08/10 02:35 by 127.0.0.1