简体   繁体   中英

Bash: How to calculate?

I need to do some basic math (720/304) * 360

but bash acts very strange:

echo "720/304 * 360" | bc
720

echo "(720/304) * 360" | bc
720

echo $(((720/304) * 360))
720

Try doing this :

 echo 'scale=2; 720/304 * 360' | bc

the scale is needed here, like I does. And better use single quotes to avoid possibly shell expansion .

With , you can do this too ( here-string ):

bc <<< 'scale=2; 720/304 * 360'

Or using here-document :

bc<<'EOF'
scale=2; 720/304 * 360
EOF

You can reverse the / and * if you can work with an integer result:

echo $((720*360/304))
852

Then it does not need temporary non-integer results (which were in your order int(720/304) = 2, 2 * 360 = 720 )

Use bc -l to get non-integer results of each operation.

echo "720/304 * 360" | bc -l

or, shorter in bash:

bc -l <<< '720/304*360'

you should do math calc with either awk or bc, if you want to have certain precision. but one should be careful to use rounding with bc . since some operation would give "unexpected" result: for example:

kent$  echo 'scale=2; 720/304 * 360' |bc 
849.60
kent$  echo 'scale=3; 720/304 * 360' |bc         
852.480
kent$  echo 'scale=4; 720/304 * 360' |bc 
852.6240

so I recommend awk :

kent$  awk 'BEGIN{printf "%.2f\n", 720/304*360}'
852.63

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM