I made a simple function where the result is e.g. 64.998472747. Is there a way this can be rounded up to 60? If it is 65.998472747 to be rounded to 70? Is this possible in Bash?

light=62.998472747
printf "$.0f" "$light"

So my function only rounds to a whole number. In this case it is going to round it to 63.

Thank you!

1 Answer 1

You can use awk like this:

awk -v n='64.998472747' 'BEGIN{print int((n+5)/10) * 10}'
60

awk -v n='67.998472747' 'BEGIN{print int((n+5)/10) * 10}'
70

awk -v n='95.0' 'BEGIN{print int((n+5)/10) * 10}'
100

awk -v n='94.99' 'BEGIN{ print int((n+5)/10) * 10}'
90

To make it generic, you can pass divisor as an argument and make a utility function as:

round() { awk -v n=$1 -v d=$2 'BEGIN{print int((n+d/2)/d) * d}'; }

Then call it as:

round 95.0000000001 10
100

round 94.9999 10
90

round 94.9999 1
95

round 95.5000000001 1
96
1  
I was searching for so long to find a solution. Thank you again! – Dankata 1 hour ago