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

Formatting numbers

I'm not sure if there is a way to format numbers so you can have a max of 2 decimal places. Any help is appreciated. Thanks.

EDIT: I realize I could simply do the math, then make it a string and use substring to shorten it to two decimal points and store it in a string instead of a number, but I was wondering if there was a more efficient way of doing this.

2 answers

✓ Accepted answer

A simple way is to use math.floor with some easy math.

function RoundToPlace(Num, Place)
	return math.floor(Num * (10^Place)) / (10^Place)
end

print(RoundToPlace(1/3, 2)) --> 0.33
print(RoundToPlace(1/3, 5)) --> 0.33333
print(RoundToPlace(5, 2)) --> 5

You can by using string.sub! Here's how:

local num = 5.4547784

function getDec(n)
	local temp = tostring(num)
	local dec = 0
	for i=1,string.len(temp) do
		if string.sub(temp, i, i) == '.' then
			dec = i
			break
		end
	end
	if dec ~= 0 then
		return tonumber(string.sub(temp, 1, dec+2))
	else
		return num
	end
end

print(getDec(num))

EDIT ON YOUR EDIT: This method will work no matter where the '.' is. 500.323 or 3.232

EDIT #2: Fixed it so it won't mess up on numbers without a decimal.

2 comments

1

Lol, I literally posted a second before you about substring. If there isn't an answer that has a better way, I will accept this.

1

I really appreciate the thought and work you have put into this, but 18cwatford's answer is shorter, more efficient, and it stays in a number value. Upvoted because it was still a great answer.

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