# If statement not working when a value contains decimal numbers

I was following a tutorial on if statements as I’m re-learning programming because it has been a long time and I stumbled upon a problem.

I was experimenting with using if statements with object propierties and I decided to use transparency.

``````local part = workspace.Part
part.Transparency = 0.6

if part.Transparency == 0.6 then
print("YES")
end
``````

When I run this script, the output doesn’t print anything, it doesn’t say that there are any errors. When I change the value to a number without decimals, however…

``````local part = workspace.Part
part.Transparency = 1

if part.Transparency == 1 then
print("YES")
end
``````

If I run that, the output prints “YES” as expected. This is confusing.
Why does this happen? Am I doing something wrong?

I can’t tell if you’re trolling but the parts transparency is set to 1 as you did in line 2 and the condition state checks the parts transparency equals to 1 as you set it to so it ran through successfully.

I don’t know what you are try to achieve in this post?

It genuinely doesn’t work for me and I don’t understand why as I’m using the same lines of code only changing the values. The if statement without decimal numbers works and the one with them doesn’t.

The problem occurs with the first if statement on the post, I provided the second one as an example of the same lines of code working but with different values that don’t include decimal points.
If you think I’m trolling I can provide a video recording of the output if necessary.

So the problem you’re running into is called floating-point error. To put it simply, decimal numbers are represented in a way that can lead to tiny inaccuracies because of how computers store them. This means that when you set `part.Transparency` to `0.6`, it might not be exactly `0.6` but something very close to it, like `0.6000001`. When you compare it with `0.6`, they are not exactly equal, so the if-statement doesn’t run.

There are a few ways to mitigate the problem you’re having. Typically people use an error margin (epsilon) to deal with such small inaccuracies. Here’s an example of how you could use one:

``````function isApproximatelyEqual(a, b, epsilon)
return math.abs(a - b) < epsilon
end

local part = workspace.Part
part.Transparency = 0.6

if isApproximatelyEqual(part.Transparency, 0.6, 0.0001) then
print("YES")
end
``````
1 Like

Thank you!! I now understand why this happens. After trying out what you wrote, I printed the exact value of Transparency after setting it to 0.6.

The exact value was 0.6000000238418579

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.