Tuesday, February 15, 2011

Math operations with decimals in ubuntu shell

The shell usually doesn't support operations with floating point numbers, but only with integers.

If you need to do something like 3.5*2 you will have to use a tool like bc:

echo "3.5*2" | bc


you can decide the number of decimals to use
echo "scale=2; 3.5135131*2" | bc

but there is a little bug: scale doesn't work with multiplications!!!
A little workaround is
echo "scale=2; 3.5135131*2/1" | bc

You will obtain the expected answer

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.