Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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!

1 comment

0

Can you show what you tried to do in code?

1 answer

✓ Accepted answer

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]))

1 comment

0

Alright, sweet. Thanks!

This discussion is preserved as it was. New answers, comments, and votes are closed.