PDA

View Full Version : correctly round in bash



roccivic
January 4th, 2010, 04:58 AM
10 divided by 6 is roughly 1.67, which should be rounded to 2, but bash rounds all numbers down.
For example:
echo $((10/6))will output 1.

How could this be solved?

Any help with this is much appreciated.

Reiger
January 4th, 2010, 05:18 AM
So there is an implicit floor() in (10/6)? In that case: $((10/6) + 0.5) ought to do.

Axos
January 4th, 2010, 05:21 AM
The man page says bash only does integer math. You'll need to use some other program to do the math and backquote the result into a string variable.

roccivic
January 4th, 2010, 05:31 AM
The man page says bash only does integer math. You'll need to use some other program to do the math and backquote the result into a string variable.
And I would be very happy with an integer result as long as it's rounded, not floored.


So there is an implicit floor() in (10/6)? In that case: $((10/6) + 0.5) ought to do.

thanks, but this actually generates a syntax error...

Axos
January 4th, 2010, 05:37 AM
You can get the remainder with the % operator. You can use that to determine whether to round up or down.

roccivic
January 4th, 2010, 05:48 AM
Oh, the modulus, of course. Thank you.

Although I just got it working anyway.

#!/bin/bash

x=10
y=6

a=$(($x/$y))
b=$((($x*10)/$y))
c=$(($b-($a*10)))
if [ "$(($c<5))" == "0" ]; then
a=$(($a+1))
fi

echo $a

ghostdog74
January 4th, 2010, 08:03 AM
use awk



awk 'BEGIN{print int((10/6)+0.5)}'

ProgramErgoSum
January 4th, 2010, 09:19 AM
I was looking around for a similar question. And, I found the bc (http://www.novell.com/coolsolutions/tools/17043.html) command. Try this :


#calc
ops="594307/1024^2"
echo "scale=4; ${ops}" | bc ;
exit 0

kaibob
January 4th, 2010, 05:31 PM
A while back I couldn't get bash or the bc utility to round correctly and did a bit of googling. For my very-simple needs, I finally decided on awk, primarily because I found a one-liner that was easily changed for floating point calculations.


awk 'BEGIN { printf "%.0f\n", 10/6 }'
2
awk 'BEGIN { printf "%.1f\n", 10/6 }'
1.7
awk 'BEGIN { printf "%.2f\n", 10/6 }'
1.67

I don't know if it's appropriate to use printf "%.0f" when rounding to a whole integer but it does work. I tried using printf "%d" but it rounded the above calculation down to 1.

akvino
January 4th, 2010, 06:27 PM
just use awk.