4

I am using <myVar>.ToString("#.##"); and getting stuff like 13.1 and 14 and 22.22

But I want 13.10 and 14.00 and 22.22

Been searching and everything coming up with how to hide zeros which is what I have, any ideas

Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
John
  • 1,407
  • 3
  • 20
  • 43
  • 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. – Petesh Nov 07 '15 at 11:25

3 Answers3

13

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,410
  • 3
  • 30
  • 63
5

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
  • 94,086
  • 102
  • 195
  • 339
1

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
  • 30,747
  • 12
  • 76
  • 133