Search code examples
bashfloating-pointroundingfixed-point

How to use expr on float?


I know it's really stupid question, but I don't know how to do this in bash:

20 / 30 * 100

It should be 66.67 but expr is saying 0, because it doesn't support float. What command in Linux can replace expr and do this equalation?


Solution

  • As reported in the bash man page:

    The shell allows arithmetic expressions to be evaluated, under certain circumstances...Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error.

    You can multiply by 100 earlier to get a better, partial result:

    let j=20*100/30
    echo $j
    

    66

    Or by a higher multiple of 10, and imagine the decimal place where it belongs:

    let j=20*10000/30
    echo $j
    

    66666