BASH rounding the float to the nearest tenth

How do you get around floats to the nearest tenths with bc. I have a variable called loadMin

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

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

Any help is appreciated.

+4
source share
2 answers

Why use bc ? printf will happily do this:

 printf "%.1f" "$loadMin" 

If you need to put the result in a variable:

 printf -v variable "%.1f" "$loadMin" 
+7
source

You can do this in one go with awk :

 loadMin=$(uptime | awk '{printf "%0.1f", $14}') 

Explanation:

  • Instead of using cut use awk instead to simplify
  • awk by default divide spaces and tabs and split each line into fields.
  • '{printf "%0.1f", $14}' : print the 14th field as a floating-point number, rounded to the nearest 1 decimal place.
+1
source

All Articles