views:

212

answers:

2

How would I round the result from two divided numbers, e.g.

3/2

As when I do

testOne=$((3/2))

$testOne contains "1" when it should have rounded up to "2" as the answer from 3/2=1.5

+7  A: 

To do rounding up in truncating arithmetic, simply add (denom-1) to the numerator.

Example, rounding down:

N/2 M/5 K/16

Example, rounding up:

(N+1)/2 (M+4)/5 (K+15)/16

To do round-to-nearest, add (denom/2) to the numerator (halves will round up):

(N+1)/2 (M+2)/5 (K+8)/16

Ben Voigt
Can you explain this a bit more? Whats denom mean for one? And I don't really get what all these brackets and letters are doing…? I feel I should know since there have been no other answers and 5+ ups
Mint
@Mint: He is showing a generalized answer using algebraic notation. Using your Bash example, it would look like this: `testOne=$(( (3 + (2 - 1) / 2))`. Even more generally, but in Bash syntax, it would be something like `answer=$(( ($numerator + ($denominator - 1) / $denomonator))`. You can also do it this way which eliminates all the dollar signs and allows more freedom with spaces (such as around the equal sign): `((answer = (numerator + (denominator - 1) / denomonator))`
Dennis Williamson
@Dennis: right, except your parentheses are unbalanced. Unfortunately it looks like Mint is a cut+paste coder with no desire to understand what's going on or how the syntactic elements of his program function.
Ben Voigt
Yeah, I made some typos on those parentheses.
Dennis Williamson
+1  A: 

bash will not give you correct result of 3/2 since it doesn't do floating pt maths. you can use tools like awk

$ awk  'BEGIN { rounded = sprintf("%.0f", 3/2); print rounded }'
2

or bc

$ printf "%.0f" $(echo "scale=2;3/2" | bc)
2
ghostdog74