Possible Duplicate:
How do I get bc(1) to print the leading zero?
I have this problem:
x=$(echo "0.81+0.02" |bc)
echo $x
Result .83
I want see 0.83, but I don't make it.
Possible Duplicate:
How do I get bc(1) to print the leading zero?
I have this problem:
x=$(echo "0.81+0.02" |bc)
echo $x
Result .83
I want see 0.83, but I don't make it.
echo
doesn't know anything about floating point numbers, it just knows about strings and integers.
You can use printf
to deal with other data types and specify precise formatting options:
printf '%.2f\n' $x
Example:
imac:barmar $ x=$(echo "0.81+0.02" |bc)
imac:barmar $ printf '%.2f\n' $x
0.83
The simplest solution is to append the result to a string already containing the "0" character.
x=0
x+=$(echo "0.81+0.02" |bc)
echo $x
If you want to be able to handle the case in which the number could be greater than 1 you can use parameter substitution instead
x=$(echo "1.81+0.02" | bc )
x=${x/^./0.}
echo $x
unfortunately the previous code won't work. The second line is meant to replace the first character, if it is a dot, with the string 0.
, but obviously I made a syntax error. I'm not very knowledgeable of regexps, but this should be exactly what you are looking for.
The following is more cumbersome, but defenetively works.
x=$(echo "1.81+0.02" | bc )
if [[ $x == .* ]]; then
x=0$x
fi
Just do it in one line:
printf '%.2f\n' $(echo 0.82+0.01 | bc)
or
echo 0.82+0.01 | printf '%.2f\n' $(bc)