Commit | Line | Data |
---|---|---|
8482fea6 | 1 | function num_round(n) { |
03c229bf SK |
2 | return int(n + 0.5) |
3 | } | |
4 | ||
8482fea6 | 5 | function num_ensure_numeric(n) { |
03c229bf SK |
6 | return n + 0 |
7 | } | |
8 | ||
8482fea6 SK |
9 | #----------------------------------- |
10 | # Why do we need num_ensure_numeric? | |
11 | #----------------------------------- | |
03c229bf SK |
12 | # awk appears to be guessing the type of an inputted scalar based on usage, so |
13 | # if we read-in a number, but did not use it in any numeric operations, but did | |
14 | # use as a string (even in just a format string!) - it will be treated as a | |
15 | # string and can lead to REALLY SURPRISING behavior in conditional statements, | |
16 | # where smaller number may compare as greater than the bigger ones, such as. | |
17 | # | |
18 | # Demo: | |
19 | # | |
20 | # $ awk 'BEGIN {x = "75"; y = "100"; sprintf("x: %d, y: %d\n", x, y); if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}' | |
21 | # 75 < 100 | |
22 | # $ awk 'BEGIN {x = "75"; y = "100"; sprintf("x: %s, y: %d\n", x, y); if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}' | |
23 | # 75 > 100 | |
24 | ||
25 | # However, once used as a number, seems to stay that way even after being | |
26 | # used as string: | |
27 | # | |
28 | # $ awk 'BEGIN {x = "75"; y = "100"; x + y; sprintf("x: %s, y: %d\n", x, y); if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}' | |
29 | # 75 < 100 | |
30 | # | |
31 | # $ awk 'BEGIN {x = "75"; y = "100"; x + y; sprintf("x: %s, y: %d\n", x, y); z = x y; if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}' | |
32 | # 75 < 100 | |
33 | # | |
34 | # $ awk 'BEGIN {x = "75"; y = "100"; x + y; z = x y; if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}' | |
35 | # 75 < 100 | |
36 | # $ awk 'BEGIN {x = "75"; y = "100"; z = x y; if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}' | |
37 | # 75 > 100 |