0 votes

print(0.1+0.2 == 0.3) # False
print("%.17f" % (0.1+0.2)) # 0.30000000000000000

For exapmle in Python:
>>> 0.1+0.2
0.30000000000000004

Why the print() function does not show the number correctly?

in Engine by (22 points)

1 Answer

+3 votes

This sounds like a formatting issue. I use C#, not GDScript, but I'd assume there's a way to increase the formatting precision.

additionally, the Mathf function IsEqualApprox() is probably what you want to use when dealing with float equality.

by (220 points)

Thanks for your answer. I know about is_equal_approx() function, but I wonder why he compares correctly in this case, and at the end shows garbage :/

Because floating point can't accurately represent all numbers, which is by design.

To represent all numbers, floating point would have to have an infinite number of bits. Since a single precision floating point number has only 32 bits, there are rounding errors introduced in unintuitive ways.

To check equality, you typically check to see if the numbers are within a given margin of error. This is what is_equal_approx() is for.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.