Search code examples
c#floating-pointdoublefloating-point-conversion

Safe Range of double which can be cast to float without any data loss


What is the safe range of double which can be cast to float without loosing any data (both with and without fraction part)

Example:

double value = 1423210126.00f; 

float floatVal = (double)value;

//floatVal = 1423210112 if we print.  There is a data loss of +14.

My Observation: If the number of digits in double is 7 digits (or 8 inclusive "."), value is successfully cast to float without loss. Is this true always?


Solution

  • at first you shouldn't add f to:

    double value = 1423210126.00f;
    

    because f is used for float and you are actually saying that your number is float while here is double.try my example:

    private void Form1_Load(object sender, EventArgs e)
    {
        double y = 123456.123456789123456789;
        float x =  123456.123456789123456789f;
        MessageBox.Show(x.ToString());
        MessageBox.Show(y.ToString());
    }
    

    you can see that the printed numbers are:

    123456.1
    123456.123456789

    so float can hold up about 6 digits and double about 14 digits and in this example if you convert double to float it will hold up 6 digits (with digits after ".") and while your number is in the float range it will be accurate otherwise you will lose data(more than 6 digits). also see the min and max value:

    enter image description here

    and see the below post for more info.

    Convert

    the 7th digit in float and 15th digit in double might be accurate or not depends if the number is in range or not.