mirror of
https://github.com/luanti-org/luanti.git
synced 2025-10-12 16:15:20 +02:00
dump[2]: avoid misleading rounding of numbers
This commit is contained in:
committed by
Lars Müller
parent
f4285a59ac
commit
98b2edeb11
@@ -7,7 +7,15 @@ local math = math
|
|||||||
local function basic_dump(o)
|
local function basic_dump(o)
|
||||||
local tp = type(o)
|
local tp = type(o)
|
||||||
if tp == "number" then
|
if tp == "number" then
|
||||||
return tostring(o)
|
local s = tostring(o)
|
||||||
|
if tonumber(s) == o then
|
||||||
|
return s
|
||||||
|
end
|
||||||
|
-- Prefer an exact representation over a compact representation.
|
||||||
|
-- e.g. basic_dump(0.3) == "0.3",
|
||||||
|
-- but basic_dump(0.1 + 0.2) == "0.30000000000000004"
|
||||||
|
-- so the user can see that 0.1 + 0.2 ~= 0.3
|
||||||
|
return string.format("%.17g", o)
|
||||||
elseif tp == "string" then
|
elseif tp == "string" then
|
||||||
return string.format("%q", o)
|
return string.format("%q", o)
|
||||||
elseif tp == "boolean" then
|
elseif tp == "boolean" then
|
||||||
|
@@ -230,3 +230,10 @@ describe("math", function()
|
|||||||
assert.equal(0, math.round(-0.49999999999999994))
|
assert.equal(0, math.round(-0.49999999999999994))
|
||||||
end)
|
end)
|
||||||
end)
|
end)
|
||||||
|
|
||||||
|
describe("dump", function()
|
||||||
|
it("avoids misleading rounding of floating point numbers", function()
|
||||||
|
assert.equal("0.3", dump(0.3))
|
||||||
|
assert.equal("0.30000000000000004", dump(0.1 + 0.2))
|
||||||
|
end)
|
||||||
|
end)
|
||||||
|
Reference in New Issue
Block a user