Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Couldn't figure out why must i need to RoundToInt before compare

Discussion in 'Scripting' started by narf03, Mar 13, 2015.

  1. narf03

    narf03

    Joined:
    Aug 11, 2014
    Posts:
    222
    The following is from the immediate window, I paused the program and evaluate the value.

    Basically i need to compare the 'x' coordinate, i always use RoundToInt when i do any rotation or movement so their x y z coordinate must be an integer. I just dont understand why goEach.transform.position.x == 1 returns false.

    > ? goEach.transform.position.x
    1
    > ? goEach.transform.position.x == 1
    false
    > ? goEach.transform.position.x == 1.0f
    false
    > ? goEach.transform.position.x - 1
    0
    > ? goEach.transform.position.x - 1 == 0
    true
    > ? goEach.transform.position.x == 1
    false
    > ? Mathf.RoundToInt(goEach.transform.position.x) == 1
    true
    >
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Long story short:
    You should not rely on float comparisons as they're not accurate and will fail quite often.
    Mathf.RoundToInt(...) returns an integer. Integers can be compared using '==' as there is nothing like imprecision.
    If you still want to compare float values, consider using Mathf.Approximately for that.
     
  3. narf03

    narf03

    Joined:
    Aug 11, 2014
    Posts:
    222
    Thanks, u saved my wall.