7

I want to format a number with the help of ToString().

I've been using <myVar>.ToString("#.##"); and getting 13.1 and 14 and 22.22.

How can I get 13.10, 14.00 and 22.22 instead?

I don't want it to hide the zeros like now.

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
John
  • 1,459
  • 4
  • 21
  • 45
  • As Royi states, use that format. It would also help to [look at the official documentation](https://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx), which explains the differences between the custom format strings. – Anya Shenanigans Nov 07 '15 at 11:25

3 Answers3

19

Because in a format string, the # is used to signify an optional character placeholder; it's only used if needed to represent the number.

If you do this instead: 0.ToString("0.##"); you get: 0

Interestingly, if you do this: 0.ToString("#.0#"); you get: .0

If you want all three digits: 0.ToString("0.00"); produces: 0.00

More here

Community
  • 1
  • 1
Nejc Galof
  • 2,538
  • 3
  • 31
  • 70
10

You can use the numeric ("N") format specifier with 2 precision as well.

Console.WriteLine((13.1).ToString("N2")); // 13.10
Console.WriteLine((14).ToString("N2"));   // 14.00
Console.WriteLine((22.22).ToString("N2")); // 22.22

Remember this format specifier uses CurrentCulture's NumberDecimalSeparator by default. If yours is not ., you can use a culture that has . as a NumberDecimalSeparator (like InvariantCulture) in ToString method as a second parameter.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
3

It is possible by using zero format specifier:

.ToString(".00");

An example:

int k=25;
string str_1 = k.ToString(".00"); // Output: "25,00"

The hash sign # means that value is optional. For example:

string str_2 = 0.ToString("0.##");// Output: "0"
StepUp
  • 36,391
  • 15
  • 88
  • 148