Question

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.

Was it helpful?

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.

OTHER TIPS

No need to store PI, unless you want to store it at a given precision.

int givenPrecision = 10;
Console.WriteLine("Pi is {0}.", Math.PI.ToString("0." + new String('#', givenPrecision)));

This will give 3.1415926536.

Explicitly convert??

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

emphasized text

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top