G
G
gvadelypa2020-02-26 16:40:15
C++ / C#
gvadelypa, 2020-02-26 16:40:15

How to output a number with a certain number of decimal places in C#?

How can I print b and c without rounding them up?
In the code below, variables b and c are rounded up

using System;
using System.IO;
class Program
{
    static void Main()
    {
        double x = Convert.ToDouble(Console.ReadLine());
        double b = Math.PI * Math.Sqrt(x);
        double c = 2 * Math.PI * x;
        Console.WriteLine("{0: 0.000}",b);
        Console.WriteLine("{0: 0.000}",c);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#, 2020-02-26
@NovichekTyrnira

two ways:
- study output specifiers from MS https://docs.microsoft.com/ru-ru/dotnet/standard/b... (additional links at the end of the topic, study them too)
- perform the necessary rounding in advance
https:/ /docs.microsoft.com/ru-ru/dotnet/api/system...
https://habr.com/ru/sandbox/76182/

G
gemnyl, 2021-06-04
@gemnyl

Hello, I'm still quite new to programming, but I would like to leave my answer in case an inexperienced youngster like me has some similar problem
. Before the output, after all the calculations, you can use this method:
double c = Math.Round(c, 2);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question