Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Best practice of the use of floats and practical double examples

Discussion in 'Scripting' started by HalfEssence, Mar 30, 2024.

  1. HalfEssence


    Dec 5, 2023

    I've been working with Unity for a few months now and habitually put the f suffix after every number. I'm wondering if this is standard / best practice or if I'm missing something since I'm still relatively new.

    Additionally, I understand that truncation can be an issue when not using a double and needing highly precise numbers, but I'm attempting to catalog in my mind a few practical examples of when to use a double so that I can avoid running into precision issues in the future. Can anyone lend me your expertise and experience to provide one or two practical examples of when a double would be necessary for unity?

    Thanks for the help!
  2. CodeSmile


    Apr 10, 2014
    If the number is supposed to be a float, suffixing with f is best practice. Consider this case:

    1/2 vs 1/2f

    0 vs 0.5f

    You almost never need high precision double values in games. Very accurate timers comes to my mind, and that's usually for profiling. And custom large-scale world engines where you want to avoid the issue below:

    A common floating point resolution issue comes with transform.position very far away from origin, in the ten thousands (see famous Minecraft examples). Nothing you can do about the odd jitter at far distances with double calculations since transform.position is a vector of three floats, so precision still gets lost upon assignment.
  3. MelvMay


    Unity Technologies

    May 24, 2013
    To add though, this is the C# language syntax and not Unity-specific so it's not a "best practice", it's simply how you specify a float (single). Most of the Unity API uses floats as it's sufficient for their use-cases.

    If you need double precision for your own code then you are free to use it. In the end, you have to know if you need larger magnitudes (etc) but it won't matter if you're feeding it all directly into an API that's consuming single-precision floats.

    Note: I'll move your post to the Scripting forum for you as the above isn't related to the job-system.
    orionsyndrome, apkdev and Bunny83 like this.