Search code examples
c#rounding

Rounding 0 to the right


I wrote a simple code to calculate the area and I wanted it to take into account 4 decimal places after the comma. However, in one of the entries in my program, it disregards the 0 at the end of the number. I wanted to know what would be the correct way to make it consider the complete number with four decimal places.

Code:

var  pi = 3.14159;
var raio = 150.00;
var area = pi * (raio * raio);
Console.WriteLine($"X = {Math.Round(area,4)}");

Output obtained: 70685,775 Expected Ouput: 70685,7750


Solution

  • var pi = 3.14159;
    var raio = 150.00;
    var area = pi * (raio * raio);
    Console.WriteLine(String.Format("X = {0:F4}", area));
    

    or

    var pi = 3.14159;
    var raio = 150.00;
    var area = pi * (raio * raio);
    Console.WriteLine($"X = {area.ToString("F4")}");
    

    or

    var pi = 3.14159;
    var raio = 150.00;
    var area = pi * (raio * raio);
    Console.WriteLine($"X = {area:F4}");