Skip to content

Instantly share code, notes, and snippets.

@Hexcede
Last active June 21, 2022 02:53
Show Gist options
  • Save Hexcede/f6afbac3d3946fc003020749c8eefa3a to your computer and use it in GitHub Desktop.
Save Hexcede/f6afbac3d3946fc003020749c8eefa3a to your computer and use it in GitHub Desktop.
Luau - Readable number (using string operations)
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
@Hexcede
Copy link
Author

Hexcede commented Jun 21, 2022

This is a much cleaner version of https://gist.github.com/Hexcede/afae4714bf92997e5ffa38e9597f72ad using string operations instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment