Floating point numbers C#

12,682

Solution 1

In plainer English, the default type assumed by the compiler for the text string 12.502 is double. A double is twice the size of a float and just like a quart can't fit in a pint, a double cannot be stored in a float unless you do a cast, which risks losing precision.

You could tell the compiler that 12.502 is actually a float which you do by adding an F or f suffix like this:

float someVariable = 12.502f;

Or:

double someVariable = 12.502;

Solution 2

Why don't you use:

float someVariable = 12.502f;

or

double someVariable = 12.502; //floating point literals are by default doubles

float is single precision floating point arithmetic, which is can't be converted to double implicitly in C#. In C# every cast that can potentially lost some information can't be implicit. float has 32 bits to store components of floating precision. double has 64 bits.

float can take values from 1.5 × 10^-45 to 3.4 × 10^38

double can take values from 5.0 × 10^-324 to 1.7 × 10^308

So you can see doubles can store much greater range of values. So if you convert from double to float you can potentially lost information.

Share:
12,682
PowerCoder
Author by

PowerCoder

Updated on June 04, 2022

Comments

  • PowerCoder
    PowerCoder almost 2 years

    I was under the impression that it is legal and conventional to declare and initialize a floating point number in this format:

    float someVariable = 12.502D;  (or M, F does not give a compiler error).
    

    However I get a compiler error:

    Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type.

    There are three types of floating point numbers in C#, right?

    1. F or f for float. (7 significant digits)
    2. D or d for Double. (15 or 16 significant digits)
    3. M or m for Decimal. (28 or 29 significant digits)

    To fix the compiler error I explicitly casted the assignment statement:

    float SomeVariable = (float) 12.525D;
    

    Did I do the right thing in this case? What is the conventional or correct way to do it declare and initialize a floating point variable that consists of a Double or a Decimal value?

  • mousio
    mousio over 11 years
    You mean the other way around? :]
  • Ilya Ivanov
    Ilya Ivanov over 11 years
    I don't know exactly if he want value of double or float
  • PowerCoder
    PowerCoder over 11 years
    Thanks, I think I was misunderstanding the whole floating point concept. I was thinking that Decimal, and Double is a subset data type of float, but float, Decimal, and Double are all stand alone and independent data types. Thanks for the plain English explanation.