tonywei
tonywei

Reputation: 725

confusing part of data type conversion

i read C# book, and there is this example. the question is, why the heck float lose the numeric "1" from int value??? isn't float have bigger magnitude?

int i1 = 100000001;
float f = i1; // Magnitude preserved, precision lost (WHY? @_@)
int i2 = (int)f; // 100000000

Upvotes: 1

Views: 75

Answers (2)

DDan
DDan

Reputation: 8276

float was not designed for big integer numbers. If you want to use big numbers and you know it is not always integers, use double.

   int i1 = 100000001;
   double f = Convert.ToDouble(i1);
   int i2 = Convert.ToInt32(f); // 100000001

If all integers and you will want to be able to do calculations with them use Int64 instead of int.

Upvotes: 0

cup
cup

Reputation: 8257

A float is a 32 bit number made up of a 24 bit mantissa and an 8 bit exponent. What happens when

float f = ii;

is an attempt to squeeze a 32 bit integer into a 24 bit mantissa. The mantissa will only store 24 bits (around 6-7 significant figures) so anything past the 6th or 7th digit will be lost.

If the assignment is made with a double, which has more significant digits, the value will be preserved.

Upvotes: 1

Related Questions