How to print a double with 4 houses after the dot in C#?

Asked

Viewed 499 times

2

static void Main(string[] args)
{
    double area, raio , pi;
    pi = 3.14159;       
    raio = Convert.ToDouble(Console.ReadLine());
    area = pi * Math.Pow(raio,2);
    Console.WriteLine("A={0}\n",area.ToString("N0"));
}

The input value is 2.00 and the expected output value is 12.5664; however, what is coming out is 125.664. How can I correct this?

1 answer

3


If you want 4 houses can not use 0. I did it in a way that avoid breaking the application by wrong typing and using what the language already offers:

using static System.Console;
using static System.Math;

public class Program {
    public static void Main(string[] args) {
        if (double.TryParse(ReadLine(), out var raio)) WriteLine($"A = {PI * Pow(raio, 2):N4}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.