Limit decimal places float c#

Asked

Viewed 3,734 times

3

I would like to show the mediadesp and mediareceit with 2 decimal places after the comma.

private void MediaReceitaseDespesas()
    {
        /* ----TOTAL / QTDE DE VALORES INFORMADOS----*/
        mediadesp = somadesp / despesas.Count;
        mediareceit = somareceit / receitas.Count;
        Console.WriteLine($"A média das despesas foi de: {mediadesp} R$");
        Console.WriteLine();
        Console.WriteLine($"A média das receitas foi de: {mediareceit} R$");
        Console.WriteLine();
        Console.ReadLine();
    }
  • you can’t tell much by your code... but try mediadesp.ToString("C2") then you can even remove that 'R$'

  • I voted for the best answer that gives the real solution. Working is different from being right: https://i.stack.Imgur.com/xG2Nn.png https://answall.com/q/219211/101

2 answers

4

The method Console.WriteLine(String, Object) (see doc) has support for Format Strings which can indicate the output format by defining a.

One of the examples in the official documentation trumps the value and immediately places the currency symbol:

decimal valor = 123.456m;
Console.WriteLine(valor.ToString("C2"));
// Escreve $123.46 no ecrã.

So you can do something like:

Console.WriteLine($"A média das receitas foi de: {0:C2}", 

You can also specify in Format String which the currency region and solves the symbol problem R$.

  • This is the right one because you decide to use decimal who has no accuracy problems.

3

Use the {0.00 formatting}

Console.WriteLine($"A média das despesas foi de: {mediadesp:0.00} R$");
...
Console.WriteLine($"A média das receitas foi de: {mediareceit:0.00} R$");

Browser other questions tagged

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