3

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?

fhnaseer
  • 7,159
  • 16
  • 60
  • 112

5 Answers5

11

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.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • ah, it is the same. There was another problem in my code. I was checking that whether this number is in between two numbers and it was giving false. It was working fine for double. But now when I rechecked this someone changed that range and condition became false. – fhnaseer Jun 27 '13 at 07:19
2

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
1

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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

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);
Praveen
  • 55,303
  • 33
  • 133
  • 164