Advertisement
pintcat

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

Sep 16th, 2024 (edited)
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.87 KB | Software | 0 0
  1. ##############################################################################################
  2. # round v1.9 - shortens integer down to a desired length & rounds it up, down or to nearest  #
  3. #  value using floating point arithmetic or parameter expansion.                             #
  4. # Handshake:                                                                                 #
  5. # $1 contains the value to be processed. Must be integer and >0.                             #
  6. # $2 contains the desired length in digits. Must be integer, >0 and < or = the length of $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_NEAR1(){ # cuts down to desired length & rounds to nearest value using parameter expansion
  18.     RND_PREP $1 $2 || return 1
  19.     printf "%.0f" "${RND_RES}e-$((${#RND_DIV}-1))"
  20. }
  21.  
  22. RND_NEAR2(){ # similar to NEAR1, but a little more accurate using floating point arithmetic
  23.     RND_PREP $1 $2 || return 1
  24.     printf $((($RND_RES+$RND_DIV/2)/$RND_DIV))
  25. }
  26.  
  27. RND_NEAR3(){ # like NEAR2, but even more precise rounding as if it's shortened recursively
  28.     RND_PREP $1 $2 || return 1
  29.     printf $((($RND_RES+$RND_DIV*10/18)/$RND_DIV))
  30. }
  31.  
  32. RND_FLOOR(){ # divides down to desired length & rounds always down
  33.     RND_PREP $1 $2 || return 1
  34.     printf $(($1/$RND_DIV))
  35. }
  36.  
  37. RND_CEIL(){ # divides down to desired length & rounds always up
  38.     RND_PREP $1 $2 || return 1
  39.     printf $((($1+$RND_DIV-1)/$RND_DIV))
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement