0

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?

s.s
  • 138
  • 8
  • 1
    Any float is exactly representable as a double, it's safe to think of the extra bits in the double all being `0`. So only those doubles which represent the same value as a float can be cast without losing some information. I've made this a comment because I suspect this is not the answer to the question you have, but to the question you have asked. – High Performance Mark Sep 14 '14 at 08:30
  • @s.s check my answer and related link. – Masoud Mohammadi Sep 14 '14 at 14:50
  • @s.s did you get your answer? – Masoud Mohammadi Sep 24 '14 at 16:42
  • @Riddle: I marked your response as an answer. I had done some tricks to optimize bandwidth in our app, where if value of data (data is of double type) < float.max. Send over the wire as float. But faced issue as stated in question. Thanks for the help. – s.s Oct 16 '14 at 14:53

2 Answers2

2

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.

Community
  • 1
  • 1
Masoud Mohammadi
  • 1,721
  • 1
  • 23
  • 41
0

float is 32 bit and double are 64. Which mean float can only store half of what double can store. So basically float can store half the size of data as what double can store.

maxspan
  • 13,326
  • 15
  • 75
  • 104
  • Not exactly try the example in question even though the value is well within float max. – s.s Oct 16 '14 at 14:45