Decimal formatting in C #

I need a function that shows no more than N decimal places, but does not fill 0 if it is not needed, therefore, if N = 2,

2.03456 => 2.03 2.03 => 2.03 2.1 => 2.1 2 => 2 

Each formatting line that I saw will contain values ​​from 2 to 2.00, which I do not want

+4
source share
3 answers

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" 
+8
source

Try the following:

 string s = String.Format("{0:0.##}", value); 
+1
source

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); } 

Usage and conclusion:

 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 
0
source

All Articles