Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round a divided number in Bash

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

like image 450
Mint Avatar asked Mar 07 '10 05:03

Mint


People also ask

How do you float a division in bash?

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.


2 Answers

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 
like image 115
Ben Voigt Avatar answered Sep 23 '22 08:09

Ben Voigt


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

like image 23
Ashish Avatar answered Sep 23 '22 08:09

Ashish