BramscoChill
BramscoChill

Reputation: 403

float invalid conversion / float unexpected behavior

I'm trying t wrap my mind around the float behavior (in C#). I have take notice of the floating point precision issue thingy. I want to convert an floating point string to an float, add + 1 to it and convert it back to a string. The input can be with (never more then 5 decimal places) or without decimals, this is different every time. The output has to be again the full notation (no Scientific notation like: 2.017002E+09F)

It seems to work correctly with the decimal conversion.

Any suggestions for the best practice to get it working with a float?

var inputDecimalStr = "2017002005"; //2017002005.55 has the same result for the float conversion
float floatRegNr = 0;
float.TryParse(inputDecimalStr, out floatRegNr); // somehow this converts to 2.017002E+09
decimal test1 = decimal.Parse(inputDecimalStr); // this seems to work
float test2 = Convert.ToSingle(test1); // somehow this converts to 2.017002E+09
float test3 = Single.Parse(inputDecimalStr, NumberStyles.Float, CultureInfo.InvariantCulture);
float test4 = 2017002005F;
float test5 = 2.017002E+09F;
float test6 = 2.017002005E+09F;
double test7 = 234423.33D;

//this works ok
test5.ToString("0." + new string('#', 339));
test1.ToString();

1 2

Upvotes: 1

Views: 282

Answers (1)

SJuan76
SJuan76

Reputation: 24895

If you use this tool that shows you the binary representation of float, you get that 2017002005 is represented as 0x4ef07204, which translated back to decimal form becomes 2017001984 (an error of 21 out of the conversion).

If you change the least significative bit of the number (i.e. the minimum change that can be registered) you get 0x4ef07205, which represents 2017002112 (107 more than 2017002005 + 1.

If this level of detail is important, you can use fixed point arithmetic. Since you only want to add 1, split the number into integer and decimal parts, add 1 to the integer part and then convert back to String each part separately.

Upvotes: 2

Related Questions