In this example,i’ll show you How to format a string as decimal in C#.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Program { static void Main(string[] args) { //this section create decimal variables. Decimal decimalValue1 = 225.25M; Decimal decimalValue2 = 225.25555M; Decimal decimalValue3 = 225.25M; Decimal decimalValue4 = 225.2M; Decimal decimalValue5 = 225.0M; Decimal decimalValue6 = 22555555.0M; Decimal decimalValue7 = 225.0M; Console.WriteLine("decimal value1: " + decimalValue1); Console.WriteLine("decimal value2: " + decimalValue2); Console.WriteLine("decimal value3: " + decimalValue3); Console.WriteLine("decimal value4: " + decimalValue4); Console.WriteLine("decimal value5: " + decimalValue5); Console.WriteLine("decimal value6: " + decimalValue6); Console.WriteLine("decimal value7: " + decimalValue7); //string format decimal using string.format method. Console.WriteLine("format decimal value: " + string.Format("{0:0.##}", decimalValue1)); Console.WriteLine("format decimal value: " + string.Format("{0:0.##}", decimalValue2)); Console.WriteLine("format decimal value: " + string.Format("{0:0.##}", decimalValue3)); Console.WriteLine("format decimal value: " + string.Format("{0:0.##}", decimalValue4)); Console.WriteLine("format decimal value: " + string.Format("{0:0.##}", decimalValue5)); Console.WriteLine("format decimal value(thousand separator): " + string.Format("{0:0,0.##}", decimalValue6)); Console.WriteLine("format decimal value(with thousand separator): " + string.Format("{0:0,0.00}", decimalValue6)); Console.WriteLine("format decimal value: " + string.Format("{0:0.##}", decimalValue7)); Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | decimal value1: 225,25 decimal value2: 225,25555 decimal value3: 225,25 decimal value4: 225,2 decimal value5: 225,0 decimal value6: 22555555,0 decimal value7: 225,0 format decimal value: 225,25 format decimal value: 225,26 format decimal value: 225,25 format decimal value: 225,2 format decimal value: 225 format decimal value(thousand separator): 22.555.555 format decimal value(with thousand separator): 22.555.555,00 format decimal value: 225 |