Formatting a number using ToString() [duplicate]

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

1

3 Answers

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

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.

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"

You Might Also Like