Shift X2 status from legacy to archived
[khatus.git] / lib / util.awk
1 function util_strip(s) {
2 sub("^ *", "", s)
3 sub(" *$", "", s)
4 return s
5 }
6
7 function util_round(n) {
8 return int(n + 0.5)
9 }
10
11 function util_ensure_numeric(n) {
12 return n + 0
13 }
14
15 #------------------------------------
16 # Why do we need util_ensure_numeric?
17 #------------------------------------
18 # awk appears to be guessing the type of an inputted scalar based on usage, so
19 # if we read-in a number, but did not use it in any numeric operations, but did
20 # use as a string (even in just a format string!) - it will be treated as a
21 # string and can lead to REALLY SURPRISING behavior in conditional statements,
22 # where smaller number may compare as greater than the bigger ones, such as.
23 #
24 # Demo:
25 #
26 # $ 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"}}'
27 # 75 < 100
28 # $ 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"}}'
29 # 75 > 100
30
31 # However, once used as a number, seems to stay that way even after being
32 # used as string:
33 #
34 # $ 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"}}'
35 # 75 < 100
36 #
37 # $ 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"}}'
38 # 75 < 100
39 #
40 # $ awk 'BEGIN {x = "75"; y = "100"; x + y; z = x y; if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}'
41 # 75 < 100
42 # $ awk 'BEGIN {x = "75"; y = "100"; z = x y; if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}'
43 # 75 > 100
This page took 0.071351 seconds and 4 git commands to generate.