Reputation: 7267
Question is real simple. I have a double which I want to convert to float.
double doubleValue = 0.00000000000000011102230246251565;
float floatValue = (float)doubleValue;
Now when I do this. Float value just goes mad. Its value is "1.110223E-16" Do I need to do something extra for this flow. Value should be 0 or 0.1 but it is not here. What the problem here?
Upvotes: 3
Views: 3484
Reputation: 98740
Double
is double-precision floating-point number but float
is single-precision floating-point number.
So normally, you can loss precision when you convert Double
to float
. 1.110223E-16
is equal something like 0.0000000000000001110223
as it representation.
If you want to round the nearest number your values, you can use Math.Round()
method.
Rounds a value to the nearest integer or to the specified number of fractional digits.
Take a look at The Floating-Point Guide
Upvotes: 1
Reputation: 56501
Actually it is giving the right value.
How about getting rid of exponent after converting to float
double doubleValue = 0.00000000000000011102230246251565;
float result = (float)doubleValue;
decimal d = Decimal.Parse(result.ToString(), System.Globalization.NumberStyles.Float);
Upvotes: 1
Reputation: 49352
Converting double
to float
will definitely be loss of precision . But the value 1.110223E-16
is exponent notation i.e. raised to power -16 that means it is something like 0.0000000000000001110223
.
You should use Math.Round() to round numbers.
Upvotes: 12
Reputation: 234635
A float is capable of representing about 6 significant figures with perfect accuracy. That's not the same thing as 6 decimal places which is what I think you were assuming.
Upvotes: 0
Reputation: 77285
The float is perfectly fine. It represents the value of the double up to the precision of a float.
1.110223E-16
is another notation for 0.0000000000000001110223
.
Upvotes: 2