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

Question How do I round a double on a cairtain position of a number?

Discussion in 'Scripting' started by stoupas, Aug 31, 2023.

  1. stoupas

    stoupas

    Joined:
    Aug 26, 2021
    Posts:
    15
    So I am making a game where you are a volleyball player and you train to get overall. The ova(ovverall) sometimes goes to 16.000000001 when I want it to be 16.1 or 16 but I dont know how to do that. Plus I have search the whole browser I think... Can anybody help? Even thoght each time I add to ova I add 0.1 I dont know how it like goes to 16.0000001
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    This is simply floating point imprecision. The numbers are stored in binary, so it cannot represent some decimal values with perfect precision. For internal calculations this is irrelevant, just remember to never compare floating point values to some hardcoded other value, as they likely wont be the exact same (instead you could compare approximately).

    Dont round the value for internal usage.
    When you display it on the GUI, simply format it there, for example using string formatting.
    Just chose and pick how many decimal places you want to see, whether always or only if they exist, and so on.
     
    Last edited: Aug 31, 2023
    CodeRonnie and Bunny83 like this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,572
    Yoreki likes this.
  4. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,184
    Here's code that will hide away the fractional:
    Code (csharp):
    1. var text = number.ToString("F0");
    If you want to see the fractional only if it's there:
    Code (csharp):
    1. var text = (number % 1 == 0) ? number.ToString("F0") : number.ToString("F1");
     
    Bunny83 likes this.
  5. stoupas

    stoupas

    Joined:
    Aug 26, 2021
    Posts:
    15
    Where do I put that... Like where I change the text or when I asign the value? where
     
  6. wideeyenow_unity

    wideeyenow_unity

    Joined:
    Oct 7, 2020
    Posts:
    728
    I'm not sure if you want "16.00" or "16.0" or just "16" returned, but whenever I have this issue I just multiply by (16.0)10 then round, or (16.00) multiply by 100 then round, and then just divide by 10 or 100 to get my result. But if you only want "16" to show but still have "16.79" to be the internal, then just make two separate variables(actual vs show).

    I'm also sure there's more fancy ways of doing it, but simplistically does it for me.