Home > Software engineering >  why is a float not printing 1.0 and printing 1 instead?
why is a float not printing 1.0 and printing 1 instead?

Time:09-23

Why is my code not printing 1.0 and printing 1 instead?

            float version = 1.0F;
        Console.WriteLine(version);
        Console.Read();

CodePudding user response:

The float overload for Console.WriteLine() calls Single.ToString() to convert the float value to a string. Single.ToString() is an overload that uses the "G" format, the general format specifier.

The general format specifier only prints decimals when required. If you want it to print with decimals, you'll need to specify that manually with a format string. Something like this would do:

float version = 1.0F;
Console.WriteLine(version.ToString("N1"));

CodePudding user response:

Try

  float version = 1.0F;
  Console.WriteLine("{0:N1}",version);

Check out the MSDN documentation, about examples of the N format

When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result.

For more : Formatting of 8568.32179:

//          N:                     8568.32
//          N0:                    8568
//          N1:                    8568.3
//          N2:                    8568.32
//          N3:                    8568.322

CodePudding user response:

I think this has to do with the compiler only printing significant digits by default. In a float, 1.0 == 1 == 1.00 == 1.000 and so on until you run out of the float precision. If the value was 1.5 or 1.05 or 1.005, all of those values would print as they are significant to the value of the float.

In order to print a specific number of digits after the decimal point, you need to tell the compiler to do this with string formatting.

More info here.

  •  Tags:  
  • c#
  • Related