Last active
June 21, 2022 02:53
-
-
Save Hexcede/f6afbac3d3946fc003020749c8eefa3a to your computer and use it in GitHub Desktop.
Luau - Readable number (using string operations)
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, decimals: number) | |
-- If the number is whole, just round and convert to a string that way | |
if math.abs(number)%1 < 1e-9 then | |
return tostring(math.round(number)) | |
end | |
-- Format as a float to the number of decimals (e.g. %.2f = 2 decimals) | |
local formatted = string.format(string.format("%%.%df", math.round(decimals)), number) | |
-- Find the decimal point | |
local point = string.find(formatted, "%.") | |
-- Find as many zeros on the end as possible (the $ anchor matches the end of the string) | |
local endZeros = string.find(formatted, "0+$", point) | |
-- If the zeros start 1 character after the decimal point, remove them and the decimal | |
if endZeros and endZeros - point == 1 then | |
return string.sub(formatted, 1, point - 1) | |
end | |
return string.sub(formatted, 1, endZeros and endZeros - 1 or #formatted) -- Remove the zeros | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a much cleaner version of https://gist.github.com/Hexcede/afae4714bf92997e5ffa38e9597f72ad using string operations instead.