locked
Scientific Notation in C# RRS feed

  • Question

  • Hello,

    I wrote this program. Can we write scientific notation in C# without String.Format?

    Thanks in advance

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace CSharp
    {
        class Class1
        {
            public static void Main()
            {
    
                Console.WriteLine("Number");
                decimal num = Convert.ToDecimal(Console.ReadLine());
    
                string s = string.Format("{0:E2}",num) ;
                Console.WriteLine(s);
                }
            }
        }
    
    

    Sunday, November 3, 2019 6:17 PM

All replies

  • Try s = num.ToString( "E2" ).

    Sunday, November 3, 2019 7:50 PM
  • Hi Arash_89,

    Is your problem solved? If so, please click "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 22, 2019 10:04 AM
  • Assuming that the number is an integer...

    This ought to work, but I haven't tested it.

    public string SciNote(int value)
            {
                int numberToConvert = value;
                string numerals = numberToConvert.ToString();
                return numerals.Substring(0, 1) + "." + numerals.Substring(1) + "10^" + numerals.Length.ToString();
            }

    If it isn't an integer, especially if it is less than 1, it would get much trickier.

    Why not use String.Format? That's easier. 

    Ethan


    Ethan Strauss

    Friday, November 22, 2019 8:34 PM