Math.round not working

hello, I was trying to use math. round for my leader stats script but it’s not working

Capture

math.round(player:WaitForChild("leaderstats"):WaitForChild("Cash").Value)

It appears as though you’re trying to do this:

local Cash = player:WaitForChild('leaderstats'):WaitForChild('Cash').Value
math.floor(Cash + 0.5)

If your cash is below x.5, it will round down to x. if your cash is above x.5, it will round up to x+1

1 Like

try using floor or ceil instead

math.floor(number + .5)
--or
math.ceil(number - .5)
2 Likes

like this?

math.ceil(Player:WaitForChild("leaderstats"):WaitForChild("Cash").Value - .5)
1 Like

correct, though both work

math.ceil(Player:WaitForChild("leaderstats"):WaitForChild("Cash").Value - .5)
math.floor(Player:WaitForChild("leaderstats"):WaitForChild("Cash").Value + .5)

is math.ceil or math.floor better?

Personally, I use math.floor(). But, it’s up to you to decide what you want.

2 Likes

It is not. If you use ceil, 0.5 rounds down to 0, which mathematicians agree is not accurate.

2 Likes

…which is why you’re subtracting 0.5 instead of adding it?

1 Like

Same thing happens. You would need to subtract 0.499999999999999

1 Like

Out of curiosity, did a benchmark

local number,output,t1,t2 = 1.56,nil,nil,nil
local now,delta = tick,nil
local ceil,floor=math.ceil,math.floor

local delta1,delta2={},{}

function Benchmark()
	t1=now()
	output=ceil(number-.5) 
	delta=now()-t1
	table.insert(delta1,delta)

	t2=now()
	output=floor(number+.5)
	delta=now()-t2
	table.insert(delta2,delta)
end

for i = 1, 1000 do
	Benchmark()
end

local avg1, avg2 = 0, 0
for i, v in delta1 do
	avg1 += delta1[i]
	avg2 += delta2[i]
end

avg1/=#delta1
avg2/=#delta2

print('math.ceil average performance: ', avg1, 'ms')
print('math.floor average performance: ', avg2, 'ms')

Results:
Math.Ceil
math.ceil average performance: 9.894371032714843 ms

Math.Floor
math.floor average performance: 9.298324584960938 ms

Difference
math.floor is 0.596046447753905 ms faster, which is negligible.

2 Likes