4

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.

sampson-chen
  • 45,805
  • 12
  • 84
  • 81

2 Answers2

8

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"
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
  • Thanks! I ended up using the latter; printf -v variable "%.1f" "$loadMin". It successfully rounded these numbers to the nearest tenth: 2.09 to 2.1--- 0.09 to 0.1--- 2.99 to 3.0 – Francis Batalla Nov 26 '12 at 21:02
1

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 make these easier
  • awk delimit on spaces and tabs by default and separates each line into fields.
  • '{printf "%0.1f", $14}': print the 14th field as a floating number, rounded to the nearest 1 decimal place.
sampson-chen
  • 45,805
  • 12
  • 84
  • 81