C# float

A loop in C# using floating point numbers:

 for (float f = 16777217f; f < 16777218f; f++) { }

Why a post about this? Well find out by running this little C# Console Application:

using System;

namespace ConsoleApplication1
{
 class Program
 {
   static void Main(string[] args)
   {
     for (float f = 16777217f; f < 16777218f; f++)
       Console.WriteLine("Hello.");
   }
 }
}

What went wrong?
The value of float f is actually 16777216, because it was rounded while storing the value.

float f = 16777217f;

Let’s explain what goes wrong with the increment by showing an example:

float f = 16777217f;
f++;

We would expect that f is now 16777218. Wrong!

float f = 16777217f;
// f is now 16777216 !!
f++;
// f is still 16777216 !! (incremented by 1 but when being saved it is rounded again)

More information about floats can be found here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s