Module:Utils/number: Difference between revisions
From Space Station 14 Wiki
No edit summary |
No edit summary |
||
Line 3: | Line 3: | ||
-- Rounds number `num` to `digits` numbers after comma. | -- Rounds number `num` to `digits` numbers after comma. | ||
function p.round_to_digit(num, digits) | function p.round_to_digit(num, digits) | ||
local str_res = string.format("%." .. digits .. "f", num) | |||
:gsub("%.?0+$", "") -- strip trailing zeros (including the dot if theres all zeros after) | :gsub("%.?0+$", "") -- strip trailing zeros (including the dot if theres all zeros after) | ||
return tonumber(str_res) | |||
end | end | ||
Line 19: | Line 21: | ||
percentage_display = percentage .. "%" | percentage_display = percentage .. "%" | ||
else | else | ||
local percentage_rounded_str = round_to_digit(percentage, digits) | local percentage_rounded_str = p.round_to_digit(percentage, digits) | ||
local was_percentage_rounded = tostring(percentage) ~= percentage_rounded_str | local was_percentage_rounded = tostring(percentage) ~= percentage_rounded_str |
Revision as of 06:18, 24 May 2025
Module documentation
|
---|
View or edit this documentation • (about module documentation) |
Contains number-related module utilities.
local p = {}
-- Rounds number `num` to `digits` numbers after comma.
function p.round_to_digit(num, digits)
local str_res = string.format("%." .. digits .. "f", num)
:gsub("%.?0+$", "") -- strip trailing zeros (including the dot if theres all zeros after)
return tonumber(str_res)
end
-- Formats a probability number, ranging from 0 to 1,
-- to a percentage with specified number of digits after comma.
-- If rounding occurs, also adds "≈".
-- @param prob Probability, from 0 to 1.
-- @param digits Digits after comma. Any more get rounded.
function p.format_probability(prob, digits)
local percentage = prob * 100
local percentage_display
if digits == nil then
percentage_display = percentage .. "%"
else
local percentage_rounded_str = p.round_to_digit(percentage, digits)
local was_percentage_rounded = tostring(percentage) ~= percentage_rounded_str
percentage_display = (was_percentage_rounded and "≈" or "") .. percentage_rounded_str .. "%"
end
return percentage_display
end
return p