27 Jun

C# String Formatting For A Number Using Scientific Notation

This example shows how to format a number using scientific notation. To do this, you can use string.Format method.

Samples:

            double number1 = 12345.67890123;
            Console.WriteLine("Default Format: " + number1);
            Console.WriteLine("Scientific Notation: " + string.Format("{0:#.##E+0}", number1));
            Console.WriteLine();

            int number2 = 123456789;
            Console.WriteLine("Default Format: " + number2);
            Console.WriteLine("Scientific Notation: " + string.Format("{0:#.##E+0}", number2));
            Console.WriteLine();

            double number3 = 12345.67890123;
            Console.WriteLine("Default Format: " + number3);
            Console.WriteLine("Scientific Notation: " + string.Format("{0:#.##E+00}", number3));
            Console.WriteLine();

Output is like below:

Default Format: 12345.67890123
Scientific Notation: 1.23E+4

Default Format: 123456789
Scientific Notation: 1.23E+8

Default Format: 12345.67890123
Scientific Notation: 1.23E+04

Leave a Reply

Your email address will not be published. Required fields are marked *