How to limit decimal places in C#

Asked

Viewed 232 times

0

I made an application to calculate the arithmetic average of 3 notes. My form has 3 Textbox that receives the note and a button that calculates the average. The result is printed on a Label, as I do to limit the amount of numbers after the ","?

 private void btnCalcular_Click(object sender, EventArgs e)
    {
        //DECLARAÇÃO DE VARIÁVEIS
        double num1, num2, num3, resultado;

        //CONVERSÃO DE STRING PARA DOUBLE
        num1 = Convert.ToDouble(txtN1.Text);
        num2 = Convert.ToDouble(txtN2.Text);
        num3 = Convert.ToDouble(txtN3.Text);

        //OPERAÇÃO DE CÁLCULO
        resultado = (num1 + num2 + num3) / 3;

        lblResult.Text = resultado.ToString();

        lblResult.Text = resultado.ToString();

        if (resultado >= 6)
        {
            MessageBox.Show("Aluno aprovado!", "Status do aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("Aluno reprovado", "Status do aluno", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
  • https://answall.com/questions/290894/casas-decimais-c

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

2

You need to format the text to be used, can not use directly, so for two houses:

$"{resultado:0.##}"

But if you want to change the value and not just learn, which is not what the code does now, then you would have to manipulate it (and it can give a different value than what you gave in the formatting, so you have to decide what is the best strategy for your scenario). It would be something like:

Round(resultado, 2)

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

There are other problems in the code, even if it works.

Browser other questions tagged

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