Nk_percent
Description
Easy way to get the percent when given two numbers.
Best way to think about this is asking: “A is what percent of B?”
If either of the two arguments is empty or the first argument is zero, the function returns “ERR%” as a single-word error message.
Otherwise, the two arguments are piped to awk
, which performs the calculation and prints the result as a percentage rounded to four decimal places. The result is then printed with a “%” symbol appended to it.
Example
[root@cloudvpsserver scripts]# nk_percent 18 254 7.08%
Code
nk_percent() { # If nothing is provided, or we try to divide by zero. Report back ERR% # We just want a single word error message since this is embeded in other scripts which expect a single word response. if [ "$1" = "" ] || [ "$2" = "" ] || [ "$1" = "0" ]; then echo "ERR%" return 0 fi # Otherwise pipe the values to awk which does some math and prints out the result. echo "$1" "$2" | awk '{printf("%.4s\n", ($1/$2)*100)}' | awk '{print $1"%"}' }