Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 404
lauriys Avatar asked Aug 10 '09 09:08

lauriys


People also ask

How use expr command in Linux?

DESCRIPTION. expr is a command line Unix utility which evaluates an expression and outputs the corresponding value. expr evaluates integer or string expressions, including pattern matching regular expressions.

How do I use Bash expr?

Expr on Integers: The output shows the subtraction value, i.e., 5. To use the “expr” command for addition, you must add “+” between the integer values. The “expr” command will calculate the sum 23 of both values 14 and 9. “/” sign between the values along with the “expr” keyword.

Can Bash do floating point math?

Although Bash arithmetic expansion does not support floating-point arithmetic, there are other ways to perform such calculations. Below are four examples using commands or programming languages available on most Linux systems.


2 Answers

bc will do this for you, but the order is important.

> echo "scale = 2; 20 * 100 / 30" | bc 66.66 > echo "scale = 2; 20 / 30 * 100" | bc 66.00 

or, for your specific case:

> export ach_gs=2 > export ach_gs_max=3 > x=$(echo "scale = 2; $ach_gs * 100 / $ach_gs_max" | bc) > echo $x 66.66 

Whatever method you choose, this is ripe for inclusion as a function to make your life easier:

#!/bin/bash function pct () {     echo "scale = $3; $1 * 100 / $2" | bc }  x=$(pct 2 3 2) ; echo $x # gives 66.66 x=$(pct 1 6 0) ; echo $x # gives 16 
like image 170
paxdiablo Avatar answered Sep 21 '22 13:09

paxdiablo


I generally use perl:

perl -e 'print 10 / 3' 
like image 42
pgl Avatar answered Sep 23 '22 13:09

pgl