Created
June 21, 2022 02:02
-
-
Save Hexcede/afae4714bf92997e5ffa38e9597f72ad to your computer and use it in GitHub Desktop.
Luau - Janky readable number rounding implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local function readableNumber(number: number, decimalCount: number?): string | |
local threshold = 1e-9 | |
local remainder = math.abs(number)%1 | |
if math.abs(1 - remainder) < threshold then | |
return tostring(math.round(number)) | |
end | |
if not decimalCount then | |
decimalCount = 2 | |
end | |
local decimals = 0 | |
repeat | |
decimals += 1 | |
until decimals >= decimalCount or (remainder * 10^decimals)%1 < threshold | |
return string.format("%s%d.%d", | |
math.sign(number) < 0 and "-" or "", | |
math.abs(math.round(if number >= 0 then math.floor(number) else math.ceil(number))), | |
math.round(remainder*10^decimals) | |
) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a (very janky and convoluted) function I wrote up fairly quickly to turn a number into a more readable string but only up to a certain number of digits. I have not benchmarked it, but I expect it's very slow relative to other forms of number to string conversion. I did this mainly just to figure out how difficult it would be, and to provide a basic starting point.
You should prefer
string.format("%2.f", number)
but if you really need to shave off those extra zeros, this may save a little time (and a need to work with strings directly which is likely still less performant)