Format double with mile and decimal

Asked

Viewed 57,329 times

22

I have the following value:

43239.110000000001

I used this command:

txtSomatorio.Text = String.Format( "{0:#.#,##}", somatorio);

I got this:

43239,11

How to do to display like this?

43.239,11

3 answers

31


Try to use it this way:

string.Format("{0:0,0.00}", somatorio); // saída = 43.239,11

Or so:

string.Format("{0:N}", 43239,11)); // saída = 43.239,11
  • 1

    the option "{0:0.0,00}" didn’t work, but "{0:N}" worked. Thank you.

  • @Jay, strange, here it works both.

  • Tin even string a = String.Format( "{0:0.0,00}", somatorio); ///"43239,110", I am using VS 2012 and only the second one worked. Go get it. kk

  • @Jota, kkkk, reversed the period and the comma. maybe that’s why.

  • 1

    Killed the riddle a = String.Format( "{0:0,0.00}", somatorio); //"43.239,11", now yes!

  • Good old boy!!!!

Show 1 more comment

25

The two answers posted are correct, but there is an addendum regarding the culture used. The answers show how normal it is to be used if you are sure that a computer is configured with a culture that gives the result you expect or even if what you expect is not actually the informed format but the monetary format that the user is expecting, i.e., the format that is on his computer (which is a good idea)

If you want to ensure that the format is the one you said on any computer you need to say what the culture to be used in the code:

string.Format(CultureInfo.GetCultureInfo("pt-BR"), "{0:N}", 43239.11));

Need to use the namespace System.Globalization.

You can even create a new culture in the way that suits you best: using System.Globalization;

public class Program {
    public static void Main() {
        var minhaCultura = new CultureInfo("pt-BR"); 
        minhaCultura.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        minhaCultura.DateTimeFormat.ShortTimePattern = "HH:mm";
        minhaCultura.NumberFormat.NumberDecimalDigits = 2;
        minhaCultura.NumberFormat.NumberGroupSeparator = "_";
        minhaCultura.NumberFormat.NumberDecimalSeparator = ",";
        System.Console.WriteLine(string.Format(minhaCultura, "{0:N}", 43239.11));
    }
}

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

Documentation.

  • Worth the compliment.

10

Just use, the number 2 is the number of decimals.

txtSomatorio.Text = somatorio.ToString("n2");

Upshot:
43.239,11

  • It worked, but I’ll use it "{0:N}", because I have to format inside gridview too. But thank you so much for the help!

  • Jay, I think the command works normally for Gridview too.

  • Then I can use on Eval!? I will test later. Living and learning, or not! kkk

  • You just need to convert first: decimal.Parse(Eval("somatorio").ToString()).ToString("n2")

Browser other questions tagged

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