Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH rounding float to the nearest tenth

How do you round floats to the nearest tenths using bc. I have a variable called loadMin

loadMin=$(uptime | cut -d" " -f14 | cut -c 1-4) 

which returns the load averages per minute with two decimal places. I.e 0.01 0.02 0.09. I need the number to be rounded to the nearest tenth. For example 0.01 rounded to 0.0 or 1.09 rounded to 1.1

Any help is appreciated.

like image 419
Francis Batalla Avatar asked Jan 15 '23 22:01

Francis Batalla


1 Answers

Why use bc? printf will happily do that:

printf "%.1f" "$loadMin"

If you need to put the result in a variable:

printf -v variable "%.1f" "$loadMin"
like image 94
gniourf_gniourf Avatar answered Jan 22 '23 08:01

gniourf_gniourf