a=-1.4
b=42273.85
awk "BEGIN {print ($a $b)}"
42272.4
I am expecting result as 42272.45, what is wrong here?
CodePudding user response:
You didn't specify a precision so awk picked one for you (%.6g
, the default for CONVFMT
, see https://www.gnu.org/software/gawk/manual/gawk.html#Built_002din-Variables):
a=-1.4
b=42273.85
awk -v a="$a" -v b="$b" 'BEGIN {printf "%.2f\n", (a b)}'
42272.45
I'm also correcting your use of shell variables in an awk script above, see How do I use shell variables in an awk script?.
CodePudding user response:
One solution to do floating point math in sh
, bash
, zsh
and more is using bc
echo "$a $b" | bc
42272.45
Using awk
you can override the internal default output format by using printf
awk -v a="$a" -v b="$b" 'BEGIN{printf("%.2f\n", a b)}'
42272.45