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.
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With