why can't I assign 1.2 value to float variable in C#? I did the same in C and C++, and it worked.
class Program
{
private readonly int a = 20;
private readonly float b;
public Program(float tmp)
{
b = tmp;
}
static void Main(string[] args)
{
Program obj1 = new Program(1.2);
Console.Read();
}
}
It gives error can not convet double to float. Why is so isn't 1.2 float value?
1.1 is not a binary float The leading '1' converts straight across, and to generate subsequent binary digits we just repeatedly multiply by two.
And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double ; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.
float has 7 decimal digits of precision. double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value. double has 15 decimal digits of precision.
Yes, an integral value can be added to a float value. The basic math operations ( + , - , * , / ), when given an operand of type float and int , the int is converted to float first. So 15.0f + 2 will convert 2 to float (i.e. to 2.0f ) and the result is 17.0f .
1.2
is a double
(8 bytes).1.2f
is a float
(4 bytes).
More details
Any literal number in your code which includes a decimal point is interpreted as a double
, not a float
, unless you mark it as a float
by appending f
.
Doubles are not automatically converted to floats, since this can result in a loss of precision.
To fix your code, you can either:
mark your literal number as a float:
Program obj1 = new Program(1.2f);
or, explicitly cast it as a float:
Program obj1 = new Program((float)1.2);
The former option should be preferred when using a numeric literal, but if you are passing a variable typed as a double, then you can use the latter one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With