This is a part of my Factorio mod Visual Signals.
This code takes a numeric value as input and returns a string for the value, for example:
-12 --> -12
1 --> 1
50 --> 50
999 --> 999
1500 --> 1.5k
24999 --> 24.9k
123456 --> 123k
1234567 --> 1.2M
12345678 --> 12M
123456789 --> 123M
1234567890 --> 1.2G
and so on...
The idea is to replicate the same way Factorio show signals in the circuit network.
The code works by determining a prefix, which simply is a potential minus sign. It then determines the middle part (the numbers and potential comma separator to use) and the suffix (the letter at the end).
The code seems to work perfectly fine and now I simply wonder: Can I improve this code somehow?
local suffixChars = { "", "k", "M", "G", "T", "P", "E" }
function CountString(count)
local absValue = math.abs(count)
local prefix = ""
if count < 0 then
prefix = "-"
end
local suffix = 1
while absValue >= 1000 do
absValue = absValue / 1000
suffix = suffix + 1
end
local str = tostring(absValue)
if absValue < 10 then
return prefix .. string.sub(str, 1, 3) .. suffixChars[suffix]
end
if absValue < 100 then
return prefix .. string.sub(str, 1, 2) .. suffixChars[suffix]
end
return prefix .. string.sub(str, 1, 3) .. suffixChars[suffix]
end