a=-1.4
b=42273.85
awk "BEGIN {print ($a + $b)}"
42272.4
I am expecting result as 42272.45, what is wrong here?
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?.
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
You might either use printf
or set OFMT
variable, which will affect print
as follows
a=-1.4
b=42273.85
awk -v a=$a -v b=$b 'BEGIN{OFMT="%.2f";print a + b}'
gives output
42272.45
Explanation: OFMT
is supposed to be floating-point conversion specification which print
uses when it encounters number, default is %.6g
. Observe that OFMT
is handy when you have multiple print
s which are supposed to output numbers in uniform way.