Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expr: non-integer argument. How to subtract dot-decimal numbers

Tags:

bash

I am trying to subtract two numbers by running the following bash script:

#!/bin/bash -x
cur_length=`cat length.txt`
cur_pos=`cat pos.txt`

diff=`$(expr $cur_length - $cur_pos)`
echo "$diff"

But the output says expr has some issue:

+++ expr 235.68 - 145.9
expr: non-integer argument
+ diff=
+ echo ''

I have searched for "expr: non-integer argument" on the net, but nothing involves dot-decimal numbers. How can I subtract numbers like this? 235.68 - 145.9

Thanks in advance.

like image 542
Coenster Avatar asked Mar 25 '14 06:03

Coenster


People also ask

How do you subtract decimals with non decimals?

To subtract decimals, follow these steps: Write down the two numbers, one under the other, with the decimal points lined up. Add zeros so the numbers have the same length. Then subtract normally, remembering to put the decimal point in the answer.

What happens when you subtract an integer from 0?

If we subtract any integer from 0, we will find the additive inverse or the opposite of the integer. Subtraction of integers is done by changing the sign of the subtrahend. After this step, if both numbers are of the same sign, then we add the absolute values and attach the common sign.

How to add and subtract integers on a number line?

Adding a negative integer will be done by moving towards the left side (or the negative side) of the number line. Any one of the given integers can be taken as the base point from where we start moving on the number line. Now, let us learn how to subtract integers on a number line. The first step is to choose a scale on the number line.

What are some examples of subtracting integers with the same sign?

Some examples of subtracting integers with the same sign are given below: Subtracting two integers with different signs is done by changing the sign of the integer that is subtracted. Then, we need to check if both the integers become positive, the result will be positive and if both the integers are negative, then the result will be negative.

What is the third and final step in adding integers?

The third and final step is to add the second integer to the number located in the previous step by taking jumps either to the left or to the right depending on whether the number is positive or negative. Let us take an example to understand this better.


1 Answers

Bash doesn't do fractions, just integers. Use bc instead:

$ echo  '235.68 - 145.9' | bc
89.78

That result can, of course, be put in a shell variable the same way that you were doing with expr:

$ diff="$(echo  '235.68 - 145.9' | bc)"
$ echo $diff
89.78
like image 75
John1024 Avatar answered Nov 09 '22 18:11

John1024