Home > Software design >  Why double becomes int?
Why double becomes int?

Time:07-15

When I run this code, I get output "System.Double, 3"

namespace NewApp 
{
    class Program
    {
        static void Main(string[] args)
        {
            double a = 1.0;
            double b = 2.7;
            a = Math.Round(b);
            Console.WriteLine(a.GetType()   ", "   a);
        }

    }
}

Why I see "3", if a is double variable and I supposed to see "3.0"?

CodePudding user response:

It is still double. You are facing with 3 instead of 3.0 because of the way Console.write works. Use this as example

Console.WriteLine(DoubleConverter.ToExactString(a))

CodePudding user response:

That's because you are saying a is Math.Round(b);

Meaning a will be 3

double a = 1.0; // a -> 1.0
double b = 2.7; // b -> 2.7
a = Math.Round(b); // a = 2.7 "rounded up" -> a = 3
Console.WriteLine(a.GetType()   ", "   a); // a is a double and 
// the value is 3 (check previous line)

Edit:

About the decimals, if you round up, you get no decimals, so its 3 instead of 3.0 I believe

Math.Round(); returns a value with no decimals
  • Related