I need to format double type so that it has minimum two decimal digits but without limitation for maximum number of decimal digits:
5 -> \"5.00\"
5.5
Something like ToString("0.00#")
should work
In this case it would be max to 3 decimal places, so add hash as required.
You can use the 0
format specificer for non-optional digits, and #
for optional digits:
n.ToString("0.00###")
This example gives you up to five decimal digits, you can add more #
positions as needed.
Try this
static void Main(string[] args)
{
Console.WriteLine(FormatDecimal(1.678M));
Console.WriteLine(FormatDecimal(1.6M));
Console.ReadLine();
}
private static string FormatDecimal(decimal input)
{
return Math.Abs(input - decimal.Parse(string.Format("{0:0.00}", input))) > 0 ?
input.ToString() :
string.Format("{0:0.00}", input);
}