Question

I'm baffled - looking at this incredibly simple code and can't find why when i enter a value for r (radius of a circle) the return value for area and perimeter is r?! It just won't calculate? Sorry for the stupid question. Is it because i want the return value with only 2 digits after the floating point?

Console.Write("Enter the circle's radius r: ");
double r = double.Parse(Console.ReadLine());
double perim = (2 * Math.PI * r);
double area = (Math.PI * (Math.Pow(r, 2)));
Console.WriteLine("The circle perimeter is: {0:2}", perim);
Console.WriteLine("The circle area is: {0:2}", area);
Was it helpful?

Solution

You need {0:0.00} instead of {0:2} for your format specifier.

Console.Write("Enter the circle's radius r: ");
double r = double.Parse(Console.ReadLine());
double perim = (2 * Math.PI * r);
double area = (Math.PI * (Math.Pow(r, 2)));
Console.WriteLine("The circle perimeter is: {0:0.00}", perim);
Console.WriteLine("The circle area is: {0:0.00}", area);

For more info see: Custom Numeric Format Strings.

Custom numeric format expects characters such as: 0, '#', and other specified here , all others characters are copied to the result.

2 is not specified in the list, it doesn't mean 2 digits after decimal instead it will copied to the result. So what ever would be the result of calculation, the output will have 2

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