Ovindo <oe*@rocketmail.com> wrote:
If I do this:
Console.WriteLine(Convert.ToString((int)(0.7f * 100)));
Console.WriteLine(Convert.ToString((int)(0.7d * 100)));
The application output is:
69
70
Can you help me to understand how conversion in c# is working?
Sure. First, look at
http://www.pobox.com/~skeet/csharp/floatingpoint.html
Then use DoubleConverter.cs (linked in the article).
Let's look at what 0.7d and 0.7f *really* are:
using System;
public class Test
{
static void Main()
{
Console.WriteLine (DoubleConverter.ToExactString(0.7f));
Console.WriteLine (DoubleConverter.ToExactString(0.7d));
}
}
Results:
0.699999988079071044921875
0.699999999999999955591079014993738383054733276367 1875
Now let's look at the actual value of the results you got when
multiplying by 100 (before the cast):
0.7f*100 = 69.9999988079071044921875
0.7d*100 = 70
Now in fact, those calculations are being done at compile time by the
C# compiler, but you get the same results if you make it happen at
runtime.
Casting to an int rounds towards zero, hence why you're getting the
results you are.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too