1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
--[[
General Lua Libraries for Lua 5.1, 5.2 & 5.3
Copyright (C) 2002-2018 stdlib authors
]]
--[[--
Additions to the core math module.
The module table returned by `std.math` also contains all of the entries from
the core math table. An hygienic way to import this module, then, is simply
to override the core `math` locally:
local math = require 'std.math'
@corelibrary std.math
]]
local _ = require 'std._base'
local argscheck = _.typecheck and _.typecheck.argscheck
_ = nil
local _ENV = require 'std.normalize' {
'math',
merge = 'table.merge',
}
--[[ ================= ]]--
--[[ Implementatation. ]]--
--[[ ================= ]]--
local M
local _floor = math.floor
local function floor(n, p)
if(p or 0) == 0 then
return _floor(n)
end
local e = 10 ^ p
return _floor(n * e) / e
end
local function round(n, p)
local e = 10 ^(p or 0)
return _floor(n * e + 0.5) / e
end
--[[ ================= ]]--
--[[ Public Interface. ]]--
--[[ ================= ]]--
local function X(decl, fn)
return argscheck and argscheck('std.math.' .. decl, fn) or fn
end
M = {
--- Core Functions
-- @section corefuncs
--- Extend `math.floor` to take the number of decimal places.
-- @function floor
-- @number n number
-- @int[opt=0] p number of decimal places to truncate to
-- @treturn number `n` truncated to `p` decimal places
-- @usage
-- tenths = floor(magnitude, 1)
floor = X('floor(number, ?int)', floor),
--- Round a number to a given number of decimal places.
-- @function round
-- @number n number
-- @int[opt=0] p number of decimal places to round to
-- @treturn number `n` rounded to `p` decimal places
-- @usage
-- roughly = round(exactly, 2)
round = X('round(number, ?int)', round),
}
return merge(math, M)
|