Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C style arithmetic with floating point values in Bash [duplicate]

How can I have the right result from this bash script?

#!/bin/bash
echo $(( 1/2 ))

I get 0 as result! So I tried to use these but without success:

$ echo $(( 1/2.0 ))
bash: 1/2.0 : syntax error: invalid arithmetic operator (error token is ".0 ")
$ echo $(( 1.0/2 ))
bash: 1.0/2 : syntax error: invalid arithmetic operator (error token is ".0/2 ")
like image 997
Alberto Avatar asked Oct 25 '12 00:10

Alberto


2 Answers

bash is not the right tool alone to use floats, you should use bc with it :

bc <<< "scale=2; 1/2"
.50

If you need to store the result in a variable :

res=$(bc <<< "scale=2; 1/2")
echo $res
like image 160
Gilles Quenot Avatar answered Nov 20 '22 03:11

Gilles Quenot


I once stumbled on a nice piece of code, which is somewhat utilizing suggestion sputnick made, but wraps it around a bash function:

function float_eval()
{
    local stat=0
    local result=0.0
    if [[ $# -gt 0 ]]; then
        result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
        stat=$?
        if [[ $stat -eq 0  &&  -z "$result" ]]; then stat=1; fi
    fi
    echo $result
    return $stat
}

Then, you can use it as:

c=$(float_eval "$a / $b")
like image 2
favoretti Avatar answered Nov 20 '22 04:11

favoretti