1

so when I'm coding Im trying to have the output print out 0.12 instead of .12. Here is my code below

echo -n "What is the total cost? ";
read cents
cost=$(echo "scale =2;$cost_in_cents/100" | bc);
percent=$(echo "scale =2;$percent / 100" | bc);
tip=$(echo "scale =2;$cost*$percent" | bc);
overall_cost=$(echo "scale =2;$cost+$tip" | bc);
average_cost=$(echo "scale =2;$overall_cost/${#GUESTS[@]}" | bc);

the output again gives me the correct output of .12 but I need a zero before the decimal place. Thanks in advance!

0
1
value=$(printf "%3.2f\n" $(echo "scale=2; 12 / 100" | bc))
0

Something like this:

$ a=$(echo "0.1 + 0.1" | bc) && echo "$a"
.2
$ a=$(printf '0%s\n' "$a") && echo $a
0.2

Alternative:

$ echo "0.1 0.1" | awk '{printf "%.2f\n", $1 + $2}'
0.20
0

Bash has printf. You can do something like printf '%.2f' $cents to print it rounded to two decimal points. If you want to assign it to a variable, use -v or use the $() structure.

Not the answer you're looking for? Browse other questions tagged or ask your own question.