I've been doing some research upon number formatting in lua, and I haven't been able to find anything which could help what I'm trying to do;
I'm trying to format numbers such as 100923 as 100.9K, and 1,000,000 as 1M etc.
Any information on how to do this would be sweet!
There is no pre-written function for this. Some tips:
n
is a number greater than or equal to 1, math.ceil(math.log(n+1)/math.log(10))
will tell you how many digits the number has (ignoring the decimal). If this comes out to be 4, you could use "K" for instance.string.format
to automatically round to the nearest 0.1: string.format("%.1f", 12.37)
produces 12.4
local letter = { [0] = "", [1] = "K", [2] = "M", --etc } local n = 100923 local numGroups = 0 local n2 = n while n2 >= 1000 do n2 = n2 / 1000 numGroups = numGroups + 1 end print(string.format("%.1f%s", n/1000^numGroups, letter[numGroups]))