Since you have the question tagged [bash]
you can simply compute the answer and save it to a variable using command substitution (e.g. r="$(...)"
) and then using [[..]]
with =~
to test if the first character in the result is [1-9]
(e.g. [[ $r =~ ^[1-9].*$ ]]
), and if the first character isn't, prepend '0'
to the beginning of r
, e.g.
(edit due to good catch by G.Man...)
r=$(echo "0.1 + 0.1" | bc) # compute / save result
sign=""; # set sign to empty str
[[ ${r:0:1} == - ]] && { # if negative
sign='-' # save - as sign
r="${r:1}" # trim from r
}
[[ $r =~ ^[1-9].*$ ]] || r="0$r" # test 1st char [1-9] or prepend 0
echo "${sign}$r" # output result with sign
Result
0.2
If the result r
is 1.0
or greater, then no zero is prepended, e.g. (as a 1-liner)
$ r=$(echo "0.8 + 0.6" | bc); sign=""; [[ ${r:0:1} == - ]] && { sign='-'; r="${r:1}"; }; [[ $r =~ ^[1-9].*$ ]] || r="0$r"; echo "${sign}$r"
1.4
$ r=$(echo "0.8 - 0.6" | bc); sign=""; [[ ${r:0:1} == - ]] && { sign='-'; r="${r:1}"; }; [[ $r =~ ^[1-9].*$ ]] || r="0$r"; echo "${sign}$r"
0.2
and negative values handled
$ r=$(echo "-0.8 + 0.6" | bc); sign=""; [[ ${r:0:1} == - ]] && { sign='-'; r="${r:1}"; }; [[ $r =~ ^[1-9].*$ ]] || r="0$r"; echo "${sign}$r"
-0.2