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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to check "if (float != 0)" if floats "are not precise"?

Discussion in 'Scripting' started by m00nkin, Feb 16, 2020.

  1. m00nkin

    m00nkin

    Joined:
    Mar 31, 2018
    Posts:
    1
    So,
    if floats are not precise and could be 0.000001 instead of 0, how do you use them in an if-statement, when you want to chek for !=0 or ==0?

    Can you maybe truncate the float? Would that even work?
     
  2. diXime

    diXime

    Joined:
    Oct 2, 2018
    Posts:
    162
    It kinda depends on how you land on zero. Most unity methods will take care of that and shouldn't get floating-point errors. Your solution depends on the amount of precision you're aiming for.
    You can round and cast to int (really not precise), using Math.Round(), or using a percentage margin, or using arithmetics (a + precision <= b && b + precision <= a).
    It really depends on your use case and the types of calculations that leads you to floating point errors.
     
  3. TuckerFlynn

    TuckerFlynn

    Joined:
    May 18, 2015
    Posts:
    10
    diXime likes this.
  4. diXime

    diXime

    Joined:
    Oct 2, 2018
    Posts:
    162
    Well, I didn't know that. Funny thing is, they say they compare within epsilon precision, and Epsilon docs explains the arithmetics solution I've suggested above. Quite cool.
     
  5. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    What exactly are you trying to do? The best approach here depends heavily on what you are trying to accomplish.