i want to make a money system where stuff should be displayed like
17223, becomes , 17.2K
any help please
If you wanted it to be displayed in thousans K, you can simply divide it by 1000, then round using math.floor, then add a K next to it using some string manipulation
local round(num)
return tostring(math.floor(num/1000)).."K"
end
String formatting and a little if statements can help you:
local function shorten(n)
if n < 1e3 then
return n
elseif n >= 1e3 and n < 1e6 then
return ("%.1fK"):format(n / 1e3)
elseif n >= 1e6 then
return ("%.1fM"):format(n / 1e6)
end
end
Some things you need to know:
- 1e3 and 1e6 is index notation / scientific notation / standard form for 1000 and 1,000,000. Index notation helps to shorten very large or very small numbers. The general way to format index notation in roblox is:
aen, where: - a is: 0 < a > 10, and it is a significant number
- n indicates how many places were moved
1100 in index notation is 1.1e3, because we moved 3 places to 1.1
- For string formatting and “%.1f” (precision), it is found on this page String formatting and conversion
If you want to add several suffixes you could use this script:
local suffixes = {"K", "M", "B", "T", "Q", "Qu", "S", "Se", "O", "N", "D"}
local function toSuffixString(n)
for i = #suffixes, 1, -1 do
local v = math.pow(10, i * 3)
if n >= v then
return ("%.3f"):format(n / v) .. suffixes[i]
end
end
return tostring(n)
end
The number always increases by 1000. The function returns a string which is the formatted number.
math.floor/ceil only works with decimals not normal numbers
You can manipulate the number so that it’ll work math.floor/math.ceil in the way that you want it to. Here’s some example code:
function RoundToPlace(num, place)
local factor = 10^place
return math.floor( (num*factor)+0.5 )/factor
end
Using this function, if you wanted to round to the 2nd decimal place, you’d do RoundToPlace(12.593, 2).
In your case, to round to the nearest hundreds place, you could do RoundToPlace(17223, -2) and it’ll return 17200.
I’m dividing the normal number with 1000, which would make it have decimal places. Also math.floor and math.ceil do work for whole numbers, they won’t error but they just would change anything.
my bad i did math.floor before dividing by 1000