Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #############################################################################################
- # round v1.7 - shortens integer down to a desired length & rounds it up, down or to nearest #
- # value using floating point arithmetic. #
- # Handshake: #
- # $1 contains the number to be processed. Must be integer and >0. #
- # $2 contains the resulting number of digits. Must be integer, >0 and <=$1. #
- # False & missing inputs give a return code 1 which can be requested for error handling. #
- # Result will be printed to stdout. #
- #############################################################################################
- RND_PREP(){ # checks if input is valid & prepares divisor for rounding
- [ $((${1##*[!0-9]*}+0)) -eq 0 ] || [ $((${2##*[!0-9]*}+0)) -eq 0 ] && return 1 || RND_RES=$1
- [ ${#1} -lt $2 ] && return 1
- RND_DIV=$(printf 1'%*s' $((${#1}-$2)) | tr " " 0)
- }
- RND_NEAR(){ # divides down to desired length & rounds to nearest value
- RND_PREP $1 $2 || return 1
- printf $((($RND_RES+$RND_DIV*10/18)/$RND_DIV))
- }
- RND_FLOOR(){ # divides down to desired length & rounds always down
- RND_PREP $1 $2 || return 1
- printf $(($1/$RND_DIV))
- }
- RND_CEIL(){ # divides down to desired length & rounds always up
- RND_PREP $1 $2 || return 1
- printf $((($1+$RND_DIV-1)/$RND_DIV))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement