You can't. bash only does integers; you must delegate to a tool such as bc
.
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
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.
Besides the mentioned bc
and awk
alternatives there are also the following:
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
echo 2k 1 3 /p | dc
echo 1/3.0 | genius
echo 1 3 div = | gs -dNODISPLAY -dQUIET | sed -n '1s/.*>//p'
echo 'pr 1/3.' | gnuplot
convert xc: -format '%[fx:1/3]' info:
or through stdin
:
echo 1/3 | { convert xc: -format "%[fx:$(cat)]" info:; }
jq -n 1/3
or through stdin
:
echo 1/3 | jq -nf /dev/stdin
echo 'print $(( 1/3. ))' | ksh
lua -e 'print(1/3)'
or through stdin:
echo 'print(1/3)' | lua
echo '1/3,numer;' | maxima
with cleaned up output:
echo '1/3,numer;' | maxima --quiet | sed -En '2s/[^ ]+ [^ ]+ +//p'
echo 1/3 | node -p
echo 1/3 | octave
echo print 1/3 | perl
echo print 1/3. | python2
echo 'print(1/3)' | python3
echo 1/3 | R --no-save
with cleaned up output:
echo 1/3 | R --vanilla --quiet | sed -n '2s/.* //p'
echo puts 1/3.0 | ruby
units 1/3
with compact output:
units --com 1/3
echo 1/3 | wcalc
with cleaned up output:
echo 1/3 | wcalc | tr -d ' ' | cut -d= -f2
print $(( 1/3. ))
or through stdin
:
echo 'print $(( 1/3. ))' | zsh
Stéphane Chazelas answered a similar question over on UL.
Improving a little the answer of marvin:
RESULT=$(awk "BEGIN {printf \"%.2f\",${IMG_WIDTH}/${IMG2_WIDTH}}")
bc doesn't come always as installed package.
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