Module:Utils/number: Difference between revisions
From Space Station 14 Wiki
No edit summary |
simplify format_probability |
||
(3 intermediate revisions by the same user not shown) | |||
Line 2: | Line 2: | ||
-- Rounds number `num` to `digits` numbers after comma. | -- Rounds number `num` to `digits` numbers after comma. | ||
-- @returns {number} | |||
function p.round_to_digit(num, digits) | function p.round_to_digit(num, digits) | ||
local str_res = string.format("%." .. digits .. "f", num) | local str_res = string.format("%." .. digits .. "f", num) | ||
Line 7: | Line 8: | ||
return tonumber(str_res) | return tonumber(str_res) | ||
end | |||
-- Rounds number `num` to `digits` numbers after comma, | |||
-- adding "≈" if rounding occured. | |||
-- @returns {string} | |||
function p.round_to_digit_formatted(num, digits) | |||
local rounded = p.round_to_digit(num, digits) | |||
if num == rounded then | |||
return tostring(rounded) | |||
else | |||
return "≈" .. rounded | |||
end | |||
end | end | ||
Line 13: | Line 26: | ||
-- If rounding occurs, also adds "≈". | -- If rounding occurs, also adds "≈". | ||
-- @param prob Probability, from 0 to 1. | -- @param prob Probability, from 0 to 1. | ||
-- @param digits Digits after comma. Any more get rounded | -- @param digits Digits after comma. Any more get rounded | ||
-- @returns {string} | |||
function p.format_probability(prob, digits) | function p.format_probability(prob, digits) | ||
local percentage = prob * 100 | local percentage = prob * 100 | ||
if digits == nil then | if digits == nil then | ||
return percentage .. "%" | |||
else | else | ||
return p.round_to_digit_formatted(percentage, digits) .. "%" | |||
end | end | ||
end | end | ||
return p | return p |
Latest revision as of 13:47, 27 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.
-- @returns {number}
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
-- Rounds number `num` to `digits` numbers after comma,
-- adding "≈" if rounding occured.
-- @returns {string}
function p.round_to_digit_formatted(num, digits)
local rounded = p.round_to_digit(num, digits)
if num == rounded then
return tostring(rounded)
else
return "≈" .. rounded
end
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
-- @returns {string}
function p.format_probability(prob, digits)
local percentage = prob * 100
if digits == nil then
return percentage .. "%"
else
return p.round_to_digit_formatted(percentage, digits) .. "%"
end
end
return p