Home > Enterprise >  Is there a built in format specifier or function in C# to convert a double value to string with a fi
Is there a built in format specifier or function in C# to convert a double value to string with a fi

Time:10-21

I need to port some Delphi code to C# and it uses Delphi's "g" format specifier. This is the documentation of the "g" specifier (from (https://docwiki.embarcadero.com/Libraries/Sydney/en/System.SysUtils.Format)

General. The argument must be a floating-point value. The value is converted to the shortest possible decimal string using fixed or scientific format. The number of significant digits in the resulting string is given by the precision specifier in the format string; a default precision of 15 is assumed if no precision specifier is present. Trailing zeros are removed from the resulting string, and a decimal point appears only if necessary. The resulting string uses the fixed-point format if the number of digits to the left of the decimal point in the value is less than or equal to the specified precision, and if the value is greater than or equal to 0.00001. Otherwise the resulting string uses scientific format.

Here are some examples:

Format("%.2g", 123456789.123456789) => 1.2E008
Format("%.3g", 123456789.123456789) => 1.23E008
Format("%.6g", 123456789.123456789) => 1.23457E008
Format("%.15g", 123456789.123456789) => 123456789.123
Format("%.15g", 2.0) => 2

Is there a built in C# .Net function which yields the same result?

CodePudding user response:

Try g (or G) format specificator (fiddle):

    string[] tests = new string[] {
        "g2",
        "g3",
        "g6",
        "g15",
    };
    
    double value = 123456789.123456789;
    
    var result = string.Join(Environment.NewLine, tests
        .Select(test => $"{value} => {value.ToString(test)} ({test})"));
    
    Console.WriteLine(result);
    
    Console.WriteLine();
    
    value = 2.0;
    
    result = string.Join(Environment.NewLine, tests
        .Select(test => $"{value} => {value.ToString(test)} ({test})"));
            
    Console.WriteLine(result);

Output:

123456789.12345679 => 1.2e 08 (g2)
123456789.12345679 => 1.23e 08 (g3)
123456789.12345679 => 1.23457e 08 (g6)
123456789.12345679 => 123456789.123457 (g15)

2 => 2 (g2)
2 => 2 (g3)
2 => 2 (g6)
2 => 2 (g15)
  • Related