skip to Main Content

Since, we would have already used datatypes "float" and "double" datatypes while defining the datatypes… Why is it necessary to add "F" or "D" at the end? Would

float a = 12.3;
double b = 12.333334656;

Why doesn’t the above declaration work? But, the below code works just fine.

float a = 12.3f;
double b = 12.333334656;

2

Answers


  1. It is not "compulsory", as stated in the question title. However, you need to be unambiguous, otherwise you would have problems when casting.

    The list below has all the explicit number types:

    var d  = 1.0d;  // double
    var d0 = 1.0;   // double
    var d1 = 1e+3;  // double
    var d2 = 1e-3;  // double
    var f  = 1.0f;  // float
    var m  = 1.0m;  // decimal
    var i  = 1;     // int
    var ui = 1U;    // uint
    var ul = 1UL;   // ulong
    var l  = 1L;    // long
    
    

    You can read more about real literals here.

    Login or Signup to reply.
  2. The issue is that expression 12.3.

    Is the above supposed to be single? (it could be)
    Is the above supposed to be double? (it could be)
    Is the above supposed to be float? (it could be).
    

    So, when the expression can be of "many" types, then you have to cast the type, or at the very least tell the computer (compiler) what type that expression is to be.

    So, say this would work:

            float a; double b;
    
            a = 12.3f;
            b = 12.333334656;
    

    So, in most cases, the compiler will assume that such "real" expressions are in fact single, or double.

    However, in the case of using a float, then you have to be explicit in the type as above shows.

    So, often we don’t notice, don’t care, and don’t worry since .net will set/guess the correct data type for you.

    However, in the case of floating vs single/double numbers? Then you have force the issue and tell .net that the expression in question is to be floating as opposed to the default assumption of single or double.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search