Print increments of 0.1 in C #

Im currently reading Code Complete Steve McConnell, specifically page 295 on floating point numbers.

When I ran the following code:

double nominal = 1.0; double sum = 0.0; for (int i = 0; i < 10; i++) { sum += 0.1; Console.WriteLine("sum: " + sum.ToString()); } if (equals(nominal,sum)) { Console.WriteLine("Numbers are the same"); } else { Console.WriteLine("Numbers are different"); } 

I got a printout 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 The numbers are different

Why didn't I get the conclusion that is supposed to happen? i.e.: 0.1 0.2 +0.30000000000000004 0.4 0.5 0.6 0.7 +0.79999999999999999 +0.89999999999999999 +0.99999999999999999 The numbers differ from each other

Is rounding C # numbers when I do an implicit conversion from double to string? I think so because when I debug the application and go through the for loop, I can see non-stop repeating decimal numbers. What do you think? Am I right or wrong?

+6
floating-point c #
source share
3 answers

double.ToString () uses a common format, which by default is 15 decimal places, if precision is not specified. This way it does a little rounding, so you see what you see. For example, 0.8999999999999999999, which you indicated in your question, is 17 decimal places. In fact, you can see the whole number by doing sum.ToString("g17") .

You can find the standard .net number formatting strings and their default precision here: http://msdn.microsoft.com/en-us/library/dwhawy9k(VS.80).aspx

+12
source share

It is in the default behavior for ToString. If you look at the amount in the debugger, you get this, which will show you the value without routing through ToString:

 0.0 0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.79999999999999993 0.89999999999999991 

An indication that the main behavior will be as you expected.

Hth

+2
source share

The short answer is: this is a floating point, so don’t count on anything, but it’s correct (for suitable "right" values)! The long responder needs to understand how a floating point works and how people work with a floating point. IIRC GNU printf (and others, I would suggest) a special case "really very close to a good base number 10".

+2
source share