How do I use floating-point arithmetic in bash?
Solution 1:
You can't. bash only does integers; you must delegate to a tool such as bc
.
Solution 2:
you can do this:
bc <<< 'scale=2; 100/3'
33.33
UPDATE 20130926
: you can use:
bc -l <<< '100/3' # saves a few hits
33.33333333333333333333
Solution 3:
bash
As noted by others, bash
does not support floating point arithmetic, although you could fake it with some fixed decimal trickery, e.g. with two decimals:
echo $(( 100 * 1 / 3 )) | sed -e 's/..$/.&/;t' -e 's/.$/.0&/'
Output:
.33
See Nilfred's answer for a similar but more concise approach.
Alternatives
Besides the mentioned bc
and awk
alternatives there are also the following:
clisp
clisp -x '(/ 1.0 3)'
with cleaned up output:
clisp --quiet -x '(/ 1.0 3)'
or through stdin
:
echo '(/ 1.0 3)' | clisp --quiet | tail -n1
dc
echo 2k 1 3 /p | dc
genius cli calculator
echo 1/3.0 | genius
ghostscript
echo 1 3 div = | gs -dNODISPLAY -dQUIET | sed -n '1s/.*>//p'
gnuplot
echo 'pr 1/3.' | gnuplot
Imagemagick
convert xc: -format '%[fx:1/3]' info:
or through stdin
:
echo 1/3 | { convert xc: -format "%[fx:$(cat)]" info:; }
jq
jq -n 1/3
or through stdin
:
echo 1/3 | jq -nf /dev/stdin
ksh
echo 'print $(( 1/3. ))' | ksh
lua
lua -e 'print(1/3)'
or through stdin:
echo 'print(1/3)' | lua
maxima
echo '1/3,numer;' | maxima
with cleaned up output:
echo '1/3,numer;' | maxima --quiet | sed -En '2s/[^ ]+ [^ ]+ +//p'
node
echo 1/3 | node -p
octave
echo 1/3 | octave
perl
echo print 1/3 | perl
python2
echo print 1/3. | python2
python3
echo 'print(1/3)' | python3
R
echo 1/3 | R --no-save
with cleaned up output:
echo 1/3 | R --vanilla --quiet | sed -n '2s/.* //p'
ruby
echo puts 1/3.0 | ruby
units
units 1/3
with compact output:
units --com 1/3
wcalc
echo 1/3 | wcalc
with cleaned up output:
echo 1/3 | wcalc | tr -d ' ' | cut -d= -f2
zsh
print $(( 1/3. ))
or through stdin
:
echo 'print $(( 1/3. ))' | zsh
Other sources
Stéphane Chazelas answered a similar question over on UL.