Reputation: 57
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?
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?
Upvotes: 3
Views: 14662
Reputation: 18843
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;
Upvotes: 7
Reputation: 222273
If you write float SomeVariable = (float) 12.525D;
, then the decimal numeral is first converted to a double and then converted to a float. In rare cases, depending on the numeral, this double rounding changes the value slightly.
Writing the numeral with an F suffix avoids this.
(If numerals were uniformly distributed in some sense, this would happen about one time in 230, since there are 29 fewer bits in a float significand than in a double significand. The problem happens when the original numeral rounds, in double, to exactly the halfway point for a float rounding [one time in 229] but would, if rounded directly to float, round in the other direction from where that halfway point is rounded to [one time in two].)
Upvotes: 0
Reputation: 23626
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.
Upvotes: 1