Can bash do floating-point arithmetic without using an external command?
No.
Bash cannot perform floating point arithmetic natively.
This is not what you're looking for but may help someone else:
Alternatives
bc
bc
allows floating point arithmetic, and can even convert whole numbers to floating point by setting the scale
value. (Note the scale
value only affects division within bc
but a workaround for this is ending any formula with division by 1)
$ echo '10.1 / 1.1' | bc -l
9.18181818181818181818
$ echo '55 * 0.111111' | bc -l
6.111105
$ echo 'scale=4; 1 + 1' | bc -l
2
$ echo 'scale=4; 1 + 1 / 1' | bc -l
2.0000
awk
awk
is a programming language in itself, but is easily leveraged to perform floating point arithmetic in your bash scripts, but that's not all it can do!
echo | awk '{print 10.1 / 1.1}'
9.18182
$ awk 'BEGIN{print 55 * 0.111111}'
6.11111
$ echo | awk '{print log(100)}'
4.60517
$ awk 'BEGIN{print sqrt(100)}'
10
I used both echo
piped to awk
and a BEGIN
to show two ways of doing this. Anything within an awk
BEGIN
statement will be executed before input is read, however without input or a BEGIN statement awk
wouldn't execute so you need to feed it input.
Perl
Another programming language that can be leveraged within a bash script.
$ perl -l -e 'print 10.1 / 1.1'
9.18181818181818
$ somevar="$(perl -e 'print 55 * 0.111111')"; echo "$somevar"
6.111105
Python
Another programming language that can be leveraged within a bash script.
$ python -c 'print 10.1 / 1.1'
9.18181818182
$ somevar="$(python -c 'print 55 * 0.111111')"; echo "$somevar"
6.111105
Ruby
Another programming language that can be leveraged within a bash script.
$ ruby -l -e 'print 10.1 / 1.1'
9.18181818181818
$ somevar="$(ruby -e 'print 55 * 0.111111')"; echo "$somevar"
6.111105
"Can bash also do floating-point arithmetic without using an external command?"
Nope.
robert@pip2:/tmp$ echo $((2.5 * 3))
bash: 2.5 * 3: syntax error: invalid arithmetic operator (error token is ".5 * 3")