1if not modules then modules = { } end modules ['util-rnd'] = {
2 version = 1.001,
3 comment = "companion to luat-lib.mkiv",
4 author = "Tamara, Adriana, Tomáš Hála & Hans Hagen",
5 copyright = "ConTeXt Development Team",
6 license = "see context related readme files"
7}
8
9
10
11
12
13
14
15local floor, ceil, pow = math.floor, math.ceil, math.pow
16local rawget, type = rawget, type
17local gsub, lower = string.gsub, string.lower
18
19local rounding = { }
20
21local methods = {
22 no = function(num)
23
24 return num
25 end,
26 up = function(num,coef)
27
28 coef = coef and pow(10,coef) or 1
29 return ceil(num * coef) / coef
30 end,
31 down = function(num,coef)
32
33 coef = coef and pow(10,coef) or 1
34 return floor(num * coef) / coef
35 end,
36 halfup = function(num,coef)
37
38 coef = coef and pow(10,coef) or 1
39 return floor(num * coef + 0.5) / coef
40 end,
41 halfdown = function(num,coef)
42
43 coef = coef and pow(10,coef) or 1
44 return ceil(num * coef -0.5) / coef
45 end,
46 halfabsup = function(num,coef)
47
48 coef = coef and pow(10,coef) or 1
49 return (num >= 0 and floor(num * coef + 0.5) or ceil(num * coef - 0.5)) / coef
50 end,
51 halfabsdown = function(num,coef)
52
53 coef = coef and pow(10,coef) or 1
54 return (num < 0 and floor(num * coef + 0.5) or ceil(num * coef - 0.5)) / coef
55 end,
56 halfeven = function(num,coef)
57
58 coef = coef and pow(10,coef) or 1
59 num = num*coef
60 return floor(num + (((num - floor(num)) ~= 0.5 and 0.5) or ((floor(num) % 2 == 1) and 1) or 0)) / coef
61 end,
62 halfodd = function(num,coef)
63
64 coef = coef and pow(10,coef) or 1
65 num = num * coef
66 return floor(num + (((num - floor(num)) ~= 0.5 and 0.5) or ((floor(num) % 2 == 1) and 0) or 1)) / coef
67 end,
68}
69
70methods.default = methods.halfup
71
72rounding.methods = table.setmetatableindex(methods,function(t,k)
73 local s = gsub(lower(k),"[^a-z]","")
74 local v = rawget(t,s)
75 if not v then
76 v = t.halfup
77 end
78 t[k] = v
79 return v
80end)
81
82
83
84local defaultmethod = methods.halfup
85
86rounding.round = function(num,dec,mode)
87 if type(dec) == "string" then
88 mode = dec
89 dec = 1
90 end
91 return (mode and methods[mode] or defaultmethods)(num,dec)
92end
93
94number.rounding = rounding
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116return rounding
117 |