0
a=-1.4
b=42273.85
awk "BEGIN {print ($a + $b)}"

42272.4

I am expecting result as 42272.45, what is wrong here?

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
nis
  • 19
  • 6

3 Answers3

2

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?.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    thanks for your help, I have corrected my variables and m good to go. Thanks a ton. – nis Nov 21 '22 at 19:02
2

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
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29
0

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 prints which are supposed to output numbers in uniform way.

Daweo
  • 31,313
  • 3
  • 12
  • 25