Format double type with minimum number of decimal digits
I need to format double type so that it has minimum two decimal digits but without limitation for maximum numb开发者_如何学Cer of decimal digits:
5 -> "5.00"
5.5 -> "5.50"
5.55 -> "5.55"
5.555 -> "5.555"
5.5555 -> "5.5555"
How can I achieve it?
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);
}
Something like ToString("0.00#")
should work
In this case it would be max to 3 decimal places, so add hash as required.
精彩评论