Search code examples
c#formattingnumber-formattingexponentialmantissa

C#: Exponential Format Specifier


I have a double number:

element.MaxAllowableConcLimitPpm = 0.077724795640326971;

I need to display it as

7.7725e-2

when I try to use it:

element.MaxAllowableConcLimitPpm.ToString("e4", CultureInfo.InvariantCulture)

it returns

7.7725e-002

How to say that mantissa should have one symbol instead of 3 ?

Format like this:

.ToString("0.0000e0")

returns

5.0000e2

instead of

5.0000e+2


Solution

  • You have to use a custom numeric format string - standard numeric format strings always have at least three digits in the exponent.

    Example with a custom string:

    using System;
    
    public class Test
    {    
        static void Main()
        {
            double value = 0.077724795640326971;
            Console.WriteLine(value.ToString("0.0000e+0")); // 7.7725e-2
        }
    }
    

    From the documentation for standard numeric format strings (emphasis mine):

    The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required.