Search code examples
c#doubledecimalpi

How can I show a decimal in a text field?


I am creating a simple console application that shows the value of PI up to a certain number of decimals. For now, I have written the following code:

namespace PIApplication
{
  static void Main()
  {
    decimal Pi = Math.PI;
    Console.Writeline("Pi is {0}.", PI);
  }
}

The reason I used {0} is that I know that this method works when it comes to Booleans but I can only assume that the 0 should be changed to something else. Can someone explain how this would work in my case?

Furthermore, I am getting an error that the system can not convert type double to decimal. I assume that this refers to the value that is defined as PI. What would I have to do to convert it from one type to the other? Do I even have to?

Thanks in advance for all the help.


Solution

  • This is how the constant PI is defined in System.Math:

    public const double PI = 3.14159 
    

    Try:

        static void Main(string[] args)
        {
            double Pi = Math.PI; 
            Console.WriteLine("Pi is {0}.", Pi); 
        }
    

    Decimal: Compared to floating-point types, the decimal type has a greater precision and a smaller range, which makes it suitable for financial and monetary calculations.