Using floating point in bash scripts requires an external calculator like GNU bc. Pipe your request to bc and note that escaping is not needed for quoted asterisks.
bash$ echo "3.8 + .4" | bc
4.2
bash$ echo '6 * 1.5' | bc
9.0
If all input values are integers, the bc option scale must be defined if you expect a floating point result.
bash$ echo '2 / 5' | bc
0
bash$ echo 'scale=2; 2 / 5' | bc
.40
You can also use the bash here string <<< to accomplish the same as a pipe of echo to bc:
bash$ echo 'scale=2; 2 / 5' | bc
.40
bash$ bc <<< 'scale=2; 2 / 5'
.40
Or, use bc -l to evoke the standard (but not default!) mathlib and see the result in floating point at max scale:
bash$ bc -l <<< '10.5 / 1'
10.50000000000000000000
No comments:
Post a Comment