tags:

views:

179

answers:

4

I'm trying to get a float number from this :

totalmark=$(expr $sum / $subjects )

Is this correct?

+5  A: 

I don't think bash has floating-point capabilities. You can try:

echo "$sum/$subjects" | bc -l
Alok
+3  A: 

Bash doesn't support floating point arithmetic. Try bc instead.

Mark Byers
+1  A: 
totalmark=$(echo "scale=4;$sum/$subjects"|bc)

By the way, three answers say that Bash doesn't support floating point arithmetic. While that is true, expr is an external program (/usr/bin/expr for me) and it's the one, in particular, in this case which doesn't support floats.

Dennis Williamson
The GNU `bc` has `scale=0` by default, which the Q presumably doesn't want. Pass the `-lq` options.
Charles Stewart
@Charles: That's why I specified a scale of 4. It could be anything you want. The `--mathlib` option (`-l`) provides a default of `scale=20` (at least on my system with bc 1.06.94). The `--quiet` option is a good idea, though.
Dennis Williamson
I'm sorry: I had not noticed you had passed the assignment in the input - I must have been daydreaming. `scale=20` is ruthless overkill, but the wanted information is there, and I tend to prefer noise in the output to noise in the shell script.
Charles Stewart
+3  A: 

bash doesn't support floats, use awk or bc/dc

eg awk

totalmark=$(awk 'BEGIN{print $sum / $subjects}')

or bc

totalmark=$(echo "scale=2;$sum/$subjects"|bc)

if you have the luxury to use different shells other than bash, try zsh or ksh

$ zsh -c 'echo $((4/1.3))'
3.0769230769230766

$ ksh -c 'echo $((4/1.3))'
3.07692307692307692
ghostdog74
Don't forget `perl -e`...
Charles Stewart
and `python -c` and `php -r` and ....
ghostdog74
@ghostdog: Fair point, but who has php installed on their client? Well, in fact, I do see that it is installed by default on Mac OS; I'm sure Apple has its reasons...
Charles Stewart
@ghostdog: Since I'm digressing anyway... It seems to me that not very many years ago that perl -e oneliners were the way most people did these things. Perl seems to be partly eclipsed these days.
Charles Stewart