Search code examples
bashfloating-pointarithmetic-expressions

C style arithmetic with floating point values in Bash


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 ")

Solution

  • is not the right tool alone to use floats, you should use 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