Advertisement
pintcat

round - shortens integer down to a desired length & rounds it up, down or to nearest value

Sep 16th, 2024 (edited)
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.50 KB | Software | 0 0
  1. #############################################################################################
  2. # round v1.7 - shortens integer down to a desired length & rounds it up, down or to nearest #
  3. #  value using floating point arithmetic.                                                   #
  4. # Handshake:                                                                                #
  5. # $1 contains the number to be processed. Must be integer and >0.                           #
  6. # $2 contains the resulting number of digits. Must be integer, >0 and <=$1.                 #
  7. # False & missing inputs give a return code 1 which can be requested for error handling.    #
  8. # Result will be printed to stdout.                                                         #
  9. #############################################################################################
  10.  
  11. RND_PREP(){ # checks if input is valid & prepares divisor for rounding
  12.     [ $((${1##*[!0-9]*}+0)) -eq 0 ] || [ $((${2##*[!0-9]*}+0)) -eq 0 ] && return 1 || RND_RES=$1
  13.     [ ${#1} -lt $2 ] && return 1
  14.     RND_DIV=$(printf 1'%*s' $((${#1}-$2)) | tr " " 0)
  15. }
  16.  
  17. RND_NEAR(){ # divides down to desired length & rounds to nearest value
  18.     RND_PREP $1 $2 || return 1
  19.     printf $((($RND_RES+$RND_DIV*10/18)/$RND_DIV))
  20. }
  21.  
  22. RND_FLOOR(){ # divides down to desired length & rounds always down
  23.     RND_PREP $1 $2 || return 1
  24.     printf $(($1/$RND_DIV))
  25. }
  26.  
  27. RND_CEIL(){ # divides down to desired length & rounds always up
  28.     RND_PREP $1 $2 || return 1
  29.     printf $((($1+$RND_DIV-1)/$RND_DIV))
  30. }
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement