Addition Substract Multiply Divide - Calculate the sum of integers or string and decimals using linux terminal
Do various math calculations like Addition,Substract,Multiply,Divide to get sum of integers or string and decimals using linux terminal
First two methods can only calculate integers so won't work with decimals
method1) using $(( ))
1 a=10
2 x="20"
3 sum=$(( $a + $x - 7 ))
4 echo $sum
method2) using expr
1 a=10
2 x="20"
3 expr $(($a + $x)) / 3
4
5 #when doing a multiply with expr we need to add backslash
6 e.g:
7 a=10
8 x="20"
9 expr $(($a + $x)) \* 3
Below methods can work with floating point numbers:
method3) using bc
1 a=10
2 x="20"
3 bc <<< "$a + $x * 2.3"
By default bc don't show floating point numbers after divide
1 open="8930.33"
2 close="9385.5"
3 bc <<< "($close - $open) / 5"
4 #we can use -l to display all decimals and zeros
5 bc -l <<< "($close - $open / 5"
But we can use scale option to display specific decimal places
1 open="8930.33"
2 close="9385.5"
3 bc <<< "scale=2;($close - $open) / 5"
bc doesn't show zero before decimal point like 0.08031418+0 -> result: .08031418
We can use printf to fix this:
1 x=0.08031418
2 y="0.3"
3 printf '%.8f' "$(echo "$x+$y" | bc)"
4 #or
5 echo "$x+$y" | bc | awk '{printf "%f ", $0}'
method4) using awk
1 open="8930.33"
2 close="9385.5"
3 awk "BEGIN {print ($close - $open) / 5.3}"
We can use printf to adjust specific decimal places:
1 open="8930.33"
2 close="9385.5"
3 awk "BEGIN {printf \"%.2f\", ($close - $open) /5.3}"
4
5#or
6 awk '{printf "%.2f ", ($1 - $2) / 5.3}' <<< "9385.5 8930.33"
7
8#or we can use any character after the results like %, ,=
9 awk '{printf "%.2f%", ($2 - $1)/$1*100}' <<< "200 250"
10
11#or calculate multiple values at one
12 awk '{print $2 / 3; print 205 * $5}' <<< "Total: 29 USD Total: 0.00014 BTC"
method5) using perl (on awk we can't ad math symbols inside a string:
e.g: awk '{print $1 "/" $2 }' <<< "82"
but we can do this with perl:
1 str="0.04 * 2"
2 perl -E "say $str "/" 2 "
NOTE:, use single quote or double quote in whole perl, don't use both quotes because sometime get error
help&moreMethods:
- https://unix.stackexchange.com/questions/40786/how-to-do-integer-float-calculations-in-bash-or-other-languages-frameworks
- http://www.masteringunixshell.net/qa4/bash-how-to-sum-variables.html
- https://www.shell-tips.com/2015/01/01/advanced-math-calculation-in-bash-using-gnu-bc/
- https://unix.stackexchange.com/questions/93029/how-can-i-add-subtract-etc-two-numbers-with-bash #bc zero decimal help
- https://unix.stackexchange.com/questions/197896/how-to-show-zero-before-decimal-point-in-bc
- https://stackoverflow.com/questions/8402181/how-do-i-get-bc1-to-print-the-leading-zero