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
While you can't use floating point division in Bash you can use fixed point division. All that you need to do is multiply your integers by a power of 10 and then divide off the integer part and use a modulo operation to get the fractional part.
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
Good Solution is to get Nearest Round Number is
var=2.5 echo $var | awk '{print int($1+0.5)}'
Logic is simple if the var decimal value is less then .5 then closest value taken is integer value. Well if decimal value is more than .5 then next integer value gets added and since awk then takes only integer part. Issue solved
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With