Number formatting is not working

1

I have this line, where I need to format a field. I did it in different ways and nothing:

lista.ForEach(e => e.Total = string.Format("{0:N}", float.Parse(e.Total)));

and so

lista.ForEach(e => e.Total = string.Format("{0:0.00}", float.Parse(e.Total)));

and more so

lista.ForEach(e => e.Total = string.Format("{0:0,0.00}", float.Parse(e.Total)));

So it comes from the bank: 205,728 and the output should be this: 205,73 and it looks like this: 205,728.00 p>

The complete method

public List<ItensLibDTO> getItensLib(int id)
        {
            var lista = contexto.ItensLibs
                .Where(itens => itens.IdOrcamento == id)
                .Select(item => new ItensLibDTO
                {
                    Produto = item.Produto,
                    Qtde = item.Qtde.ToString(),
                    Unitario = item.Unitario.ToString(),
                    Custo = item.Custo.ToString(),
                    CustoDiario = item.CustoDiario.ToString(),
                    UltCondicao = item.UltCondicao.ToString(),
                    Total = item.Total.ToString()
                }).ToList();

            lista.ForEach(e => e.UltCondicao = new DateTime(1800, 12, 28).AddDays(float.Parse(e.UltCondicao)).ToString("dd/MM/yyyy"));
            lista.ForEach(e => e.Total = string.Format("{0:N}", float.Parse(e.Total)));

            return lista;
        }
    
asked by anonymous 12.09.2017 / 00:15

2 answers

1

Just to register, what you're doing is a huge mess and, based on this, you can say that your problems will not end here. The correct one should be to solve the problem from the beginning and start doing everything correctly.

Given the legal warning, let's get the solution. The problem here is that the number is in the American format, from there begins the mess with cultures.

What you need to do is convert the number to double using the original format and then convert to string again, this time using the format you want in the presentation.

string.Format(new CultureInfo("pt-BR"), "{0:N}", 
              double.Parse("250.728", new CultureInfo("en").NumberFormat));
    
12.09.2017 / 01:54
1

To do this, you can join the CultureInfo with the method ToString :

lista.ForEach(e => e.Total = float.Parse(e.Total).ToString("0.00").Replace(".", ","));

Do not forget to add the use of the namespace where the CultureInfo class is located:

using System.Globalization;

Explanation:

new CultureInfo("pt-BR") : Format the text according to the Brazilian standard, that is, with commas in numbers that have decimal places.

"0.00" : Indicates that the text should only have 2 decimal places.

    
12.09.2017 / 00:30