-2

I have the following numbers as strings; 22570438, 22570481, 22570480.

var listOfStrings = new List<string> { "22570438", "22570481", "22570480" };

foreach (var val in listOfStrings)
{
    float numTest = 0;
    numTest = Convert.ToInt64(float.Parse(val));
    numTest = long.Parse(val);
    numTest = float.Parse(val.ToString().TrimStart().TrimEnd(), CultureInfo.InvariantCulture.NumberFormat);
}

For number, 22570438, in these 3 instances the number returned is 22570438, as with 22570480 But for 22570481, these 3 instances return 22570480. Code below is a sample how I'm doing the testing and not an code issue. I have tried it in other projects and still getting same result.

Has anyone experience this issue and is it a compiler issue when converting 22570481 to a float ??

I tried finding similar questions but If anyone knows a post that could help please reply with link.

Derrick Moeller
  • 4,808
  • 2
  • 22
  • 48
  • 3
    22 570 480 > 8 388 608 ... and 8 388 608 is the point where IEEE 754 cannot be precise (for integers) for [float](https://en.wikipedia.org/wiki/Single-precision_floating-point_format) ... [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Selvin Feb 13 '20 at 16:36

1 Answers1

1

float has limited precision; it can't accurately store arbitrary integers beyond a certain size, and it doesn't have the precision to retain what you want here.

Consider using int, decimal or double instead.

It is not a compiler bug or a runtime bug. It is a fundamental feature of floating point arithmetic (in this case 32-bit IEEE 754 floating points)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900