Bash Floating point calculations

If you are using any scripting language you wont often would require a floating point calculation, but should you require you will have it. Scripting languages like Python, Ruby, etc. But if you consider Bash as not just a Shell interpreter but also as a language then you will be to a surprise that it does not have a floating point calculation inbuilt. So if you have to perform any floating point calculation you need external tool such as bc or awk. We will cover on how to do them. There are basically 4 operation you can perform Addition, Subtraction, Multiplication, Division.

VariableA=1.1
VariableB=2.2
AddResult=$(echo "$VariableA+$VariableB"|bc)
$echo $AddResult
3.3
or you can also use
AddResult=$(bc<<<"$VariableA+$VariableB")
$echo $AddResult
3.3
SubResult=$(echo "$VariableB-$VariableA"|bc)
$echo $SubResult
1.1
or you can also use
SubResult=$(bc<<<"$VariableB-$VariableA")
$echo $SubResult
1.1

If you subract the other way you get a negative value like this
SubResult=$(bc<<<"$VariableA-$VariableB")
$echo $SubResult
-1.1
MulResult=$(echo "$VariableB*$VariableA"|bc)
$echo $MulResult
2.4
or you can also use
MulResult=$(bc<<<"$VariableB*$VariableA")
$echo $MulResult
2.4
DivResult=$(echo "$VariableB/$VariableA"|bc)
$echo $DivResult
2.4
or you can also use
DivResult=$(bc<<<"$VariableB/$VariableA")
$echo $DivResult
2.4

If you want reminder then you can like this

RemResult=$(echo "$VariableD%$VariableA"|bc)
$echo $RemResult
.4
or you can also use
RemResult=$(bc<<<"$VariableD%$VariableA")
$echo $RemResult
.4

for more information read man page

man bc

Leave a Reply

Your email address will not be published. Required fields are marked *