Search Unity

converting a double to a float

Discussion in 'Scripting' started by SimonAlkemade, Aug 31, 2011.

  1. SimonAlkemade

    SimonAlkemade

    Joined:
    Feb 4, 2009
    Posts:
    432
    How do I cast a double to a float. I can only retrieve a double but I need a float the decrease in accuracy is not important.

    I tried ToFloat() but apparently that does not exits.

    Any ideas?
     
    Sheepking likes this.
  2. rokstar234

    rokstar234

    Joined:
    Mar 29, 2011
    Posts:
    94
    theres two way i can think of,

    Code (csharp):
    1.  
    2.  
    3. YourDouble as float;
    4.  
    but this one wont work because float is not a null-able type thus can't converted this way but


    Code (csharp):
    1.  
    2. (float)YourDouble
    3.  
    this will work, i don't know why or how these two conversions are different but this one will work for sure
     
  3. SimonAlkemade

    SimonAlkemade

    Joined:
    Feb 4, 2009
    Posts:
    432
    i'll try that thanks, now that I think of this does make sense!
     
  4. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    As you said "as" can return null - since float cannot be null it won't work.

    You use "as" for casting objects when your not 100% sure it will work and don't want to deal with exceptions.

    http://msdn.microsoft.com/en-us/library/cscsdfbt(v=VS.100).aspx
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    System.Convert.ToSingle. (Remember that "float" is an alias for System.Single.)

    --Eric
     
    Rick8684n likes this.