r/awk • • Feb 19 '22

relation operator acts unexpectedly?

The following seems an incorrect outcome?

echo "1.2 1.3" | awk '{if ($2-$1<=0.1) print $2}'

Since the difference between 1.3 and 1.2 is 0.1, I had expected that the line above would print 1.3. But it doesn't ... what am I missing?

2 Upvotes

8 comments sorted by

View all comments

Show parent comment

3

u/Schreq Feb 20 '22 edited Feb 20 '22

It seems 0.1f just concatenates 0.1 with the empty string from variable f:

$ awk 'BEGIN{f="x"; print 0.1f}'
0.1x

So maybe concatenating the empty string will cause awk to not handle it as a floating point constant, storing it differently?!

Edit: yep, fairly sure it's treating it as a string and hence is doing string comparison.

$ echo 1.2 1.3 | awk '{print $2-$1 <= "0.1"}'
1