Sometimes we need to format Numbers with Positive (+) and Negative (-) signs which we can achieve easily using string formatting.
Given below is string format which has three parts separated by a semicolon, the first is for positive numbers, the second is for negative numbers and the third is for zero.
- private static double posNumber = 224.233;
- private static double negNumber = -226.256;
- private static double zeroNumber = 0;
-
- static void Main(string[] args)
- {
- string format = "+#.##;-#.##;(0)";
-
- Console.WriteLine(posNumber.ToString(format));
- Console.WriteLine(negNumber.ToString(format));
- Console.WriteLine(zeroNumber.ToString(format));
-
- Console.ReadLine();
- }
Output
+224.23
-226.26
(0)