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

aaaaaahhhhhhh, Why does my for loop only go up to 0.99?

for i = 0,1,0.01 do print(i) end

IT only prints up to .99 and idk why, I put this code in the command bar and it prints to .99 aswell

4 comments

1

This is normal take a look at http://wiki-origin.roblox.com/index.php?title=Lua_errors Tricky Mistakes.

0

I think that's because that essentially is this in c language: for(int i = 0,i < 1,i += 0.01){ }

0

but how do i evade this effect i want it to end at 1

0

you could add a line like if i >= 1 then break

2 answers

✓ Accepted answer

The issue is caused by floating point precision error. Due to the 100 addition operations you're doing, the binary value loses precision as it has a finite length and the bit-representation gets too long.

You can see the 0.99 you're getting is not exactly 0.99 with this piece of code:

for i = 0, 1, 0.01 do
	print(i == 0.99)
end

It is generally considered a bad practice to use decimals in for loops due to this very issue. A way better idea is to simply use integers and divide them back into the decimal form if necessary:

for i = 0, 100 do
	i = i / 100
	print(i)
end

It might be a simple fix. Either:

  • Add 1 to your i variable if you aren't going to be using 0
for i = 0, 1, 0.01 do
	print(i + 1)
end
  • Or instead of 1, put 1.01 if you are going to use 0
for i = 0, 1.01, 0.01 do
	print(i)
end

1 comment

0

add .01, not 1

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