Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I format numbers such as 10,000 as 10K?

Asked by 5 years ago

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!

0
Can you show what you tried to do in code? Zikelah 20 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago

There is no pre-written function for this. Some tips:

  • If 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.
  • You could repeatedly divide the number by 1000 while it's >= 1000 and keep track of how many times you do this
  • You can use string.format to automatically round to the nearest 0.1: string.format("%.1f", 12.37) produces 12.4
  • You can use a table to choose which letter to use:
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]))
0
Alright, sweet. Thanks! EvilMessor 9 — 5y
Ad

Answer this question