Home > OS >  How to make it, so there are only 3 or 4 number after a comma in C#?
How to make it, so there are only 3 or 4 number after a comma in C#?

Time:09-16

I am new in programming completely. This is my first lesson. I know 0%. We are trying OOP Windows Form app. SO how can I make it so there is only 3/4 numbers after the comma. The Code:

double TgG(double x)
{
    return Math.Tan(x*Math.PI/180);
} //TanG

private void button1_Click(object sender, EventArgs e)
{
    double x, y;
    x= double.Parse(textBox1.Text);
    y = TgG(x);
    label2.Text = y.ToString();
} //TanG(x) button click

CodePudding user response:

In C# you choose the format when you dispaly a value or convert it to a string. To do that use this overload of ToString with the following format:

// Format as a numeric value with 3 decimal places.
label2.Text = y.ToString("N3");

The documentation linked above gives several other built-in formats, and you can specify custom formats as well.

CodePudding user response:

Use the .Round() method. Here's an example of using it:

    //Rounding 1.678 to 2 decimal places
    Math.Round(1.678, 2); //1.68
  • Related