Search code examples
c#.netwinformsfloating-point-conversionstring-conversion

Why does my floating point value have an `E` character when I convert it to a string?


txtDebugLog.Invoke(new MethodInvoker(delegate()
{
    fps.Frame();
    ggg = fps.GetFPS();
    txtDebugLog.Text = String.Format("{0}\r\n{1}", ggg, txtDebugLog.Text);
})

txtDebugLog is a TextBox.

Using a breakpoint i see on ggg in this example it's value is:

0.00000102593151

Then i click on continue and see in the TextBox:

1.025932E-06

Solution

  • Your floating point value ggg has a very small value. When you convert it to a string, as happens in this call

    String.Format("{0}\r\n{1}", ggg, txtDebugLog.Text); 
    

    it will be converted to a string that uses an exponential format to represent that value. You can read about what an exponential format is, also referred to as scientific notation, here.

    If you want to use a different format, you have to specify that yourself. Many standard formats are available, that you can explicitly specify when doing a conversion. The conversion of a double to a string using a specific format can be done by calling the double.ToString(format) method.

    Several standard formats are available and listed there, including the output you will get from them.

    The default format that is used if you do not specify one, is the General Format Specifier ("G"), which:

    Converts a number to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present. The precision specifier defines the maximum number of significant digits that can appear in the result string.