How to subtract float values in shell script

I have a script which uses float values but some how i am not able to subtract two floats.

This is the sample code

#!/bin/bash

p="1"
h="10"
m=$(echo "3.5"| bc -l)
for (( c=$p; c<=$h; c++ ))
do
   r=$(echo "($p-$m)"| bc -l)

   echo "Z $c $m $r"
done

and this is the result

Z 1 3.5 -2.5
Z 2 3.5 -2.5
Z 3 3.5 -2.5
Z 4 3.5 -2.5
Z 5 3.5 -2.5
Z 6 3.5 -2.5
Z 7 3.5 -2.5
Z 8 3.5 -2.5
Z 9 3.5 -2.5
Z 10 3.5 -2.5
Asked By: Eka

||

Change the line

   r=$(echo "($p-$m)"| bc -l)

to

   r=$(echo "($c-$m)"| bc -l)

as it isn’t $p but $c that is changed by the loop.

Answered By: Florian Diesch

bash doesn’t support floating point arithmetic. ksh and zsh do. POSIXLy, you could use either bc as Florian’s answer suggests, or awk. For instance,

$ awk 'BEGIN{print 2.5+3.7}'
6.2

Ubuntu also comes with Python and Perl which are more than capable of performing floating point calculations.

$ perl -le 'print(2.5+3.7)'
6.2

$ python3 -c 'print(2.5+3.7)'
6.2

See also a very extensive list of other options: How to do integer & float calculations, in bash or other languages/frameworks?

Note also that according to POSIX Shell Language standard in arithmetic expansion $((...)):

Only signed long integer arithmetic is required…As an extension, the shell may recognize arithmetic expressions beyond those listed.

So omission of floating point arithmetic from bash and /bin/dash is in accordance with POSIX specs.

Answered By: Sergiy Kolodyazhnyy

I know this is late but as the result appeared on Google, someone might read this. The solution is to write it as "$a- $b". The space makes it work for me.

Answered By: Vipxpert
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.