Decimal Formatting in C#
I want a function that shows at most N decimal places, but does not pad 0's if it is unnecessary, so if N = 2,
2.03456 => 2.03
2.03 => 开发者_JS百科2.03
2.1 => 2.1
2 => 2
Every string formatting thing I have seen will pad values like 2 to 2.00, which I don't want
How about this:
// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
Try this:
string s = String.Format("{0:0.##}", value);
I made a quick extension method:
public static string ToString(this double value, int precision)
{
string precisionFormat = "".PadRight(precision, '#');
return String.Format("{0:0." + precisionFormat + "}", value);
}
Use and output:
double d = 123.4567;
Console.WriteLine(d.ToString(0)); // 123
Console.WriteLine(d.ToString(1)); // 123.5
Console.WriteLine(d.ToString(2)); // 123.46
Console.WriteLine(d.ToString(3)); // 123.457
Console.WriteLine(d.ToString(4)); // 123.4567
精彩评论