Wednesday, April 13, 2022

[SOLVED] How to round to 1 decimal in bash?

Issue

I am trying my first script on bash and I am not able to round (not truncate).

So, I am getting 55.08 and I would like to convert it to 55.1

promedio=$(echo "scale=2; $lineas/($dias*24)" | bc)

Note that I am currently using scale=2 because scale=1 produces 55.0.

Thank you all :)


Solution

This is not so much a bash question as a bc one, but bc doesn’t round. The easiest approach is probably just to add .05 after the division, then set scale to 1 and divide by 1 to force truncation.

You can do that by using a variable inside bc to hold the unrounded result:

promedio=$(bc <<<"scale=2; p=$lineas/($dias*24); scale=1; (p+0.05)/1")

Or you could do it all in one go by throwing in an extra multiplication by 10, rounding at that magnitude, and then dividing back down:

promedio=$(bc <<<"scale=1; (10*$lineas/($dias*24)+0.5)/10")


Answered By - Mark Reed
Answer Checked By - Mary Flores (WPSolving Volunteer)