Reputation: 95
Hi i am tring to produce flaoting point precision using the following code
let number1=0 number2=0 operator=+
printf "%0.2f\n" result=$(( number1 $operator number2 ))
The code works without the printf but i cannot figure out how to perform negative(-) calcs and floating points?
Upvotes: 2
Views: 3645
Reputation: 95
In the end i figured it out!
result=$(echo "scale=4; (( $number1 $operator $number2 ))" | bc)
Upvotes: 0
Reputation: 14778
Bash does not support floating point calculations, so, either you multiply the numbers being operated by as many zeros as decimals you want:
# 10.321 - 123.01
result=$(( 10321 - 123010 ))
echo ${result:0:-3}.${result:${#result} - 3}
Or simply use another tool to do this, like bc
:
echo "scale=2; 10.321 - 123.01" | bc
Also, the syntax you've used is not valid; you should have:
printf "%0.2f\n" $(( number1 $operator number2 ))
Upvotes: 2