4

Why won't this statement work?

total=`expr $mPercent / 100 "*" .482 + $fPercent / 100 "*" .518`

mPercent is a number as a result of an awk statement, as well as fPercent. I also get "expr: non-numeric argument" as an error message.

NOTE: For the purposes of his question, let's say that the 2 variables have the value 3.27.

  • This is irrelevant to your issue, but you should not be using backticks, they're deprecated. Use $() instead, like so: total=$(expr ...) – nyuszika7h Oct 31 '14 at 11:56
  • For that matter, expr itself is obsolete for arithmetic; use $(( ... )) instead. – chepner Oct 31 '14 at 19:00
2

bash cannot do floating point operations, only integers. I suggest to use bc -l instead:

$ mPercent='2.72'
$ fPercent='3.14'
$ bc -l <<< $(echo "$mPercent / 100 "*" .482 + $fPercent / 100 "*" .518")
.02937560000000000000
2

The expr command can only do integer or string manipulations. Look at the man page for this guidance:

Operands are either integers or strings. Integers consist of one or more decimal digits, with an optional leading '-'. 'expr' converts anything appearing in an operand position to an integer or a string depending on the operation being applied to it.

So to perform this type of operation you'll need to enlist a command line caluclator such as bc.

Example

$ mPercent='.123'
$ fPercent='.345'
$ echo "$mPercent / 100 * .482 + $fPercent / 100 * .518" | bc -l
.00237996000000000000

NOTE: expr is not part of Bash, it's a standalone executable that's part of the package coreutils. On systems using RPMs you can see this like so:

$ rpm -qf $(type -p /usr/bin/expr)
coreutils-8.21-13.fc19.x86_64

Using your data that you provided in the comments of 3.27 for the 2 variables yields the following:

$ mPercent='3.27'
$ fPercent='3.27'
$ echo "$mPercent / 100 * .482 + $fPercent / 100 * .518" | bc -l
.03270000000000000000
1

My suggestion is that use bc for arithmetic operation and <<< (Here String) for inputting the values to bc.

$ mPercent=3.27
$ fPercent=3.27

$ bc -l <<< "$mPercent / 100 * .482 + $fPercent / 100 * .518"
.03270000000000000000

Here -l option to bc will allow you to use floating point arithmetic with more mathematical functions.

  • +1, I have used unnecessary echo. – jimmij Oct 31 '14 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.