SoFunction
Updated on 2025-03-06

Usage in C#

Usage of C# ()

Data of double type in C# sometimes needs to be formatted and displayed as a string (preserving N-digit significant digits or preserving N-digit decimals), and you can use the ("parameter") method.

Here are some common methods

(F)Fixed point:string str1=("f1");              //Retain one decimal and round it. Result: 3.1
(F)Fixed point:string str2=("f2");              //Keep two decimal places and round them up. The following is an analogy. Result: 3.14
(N)Number:string str2=("N");                   //Reserve Result: 3.14
(G)General (default):string str2=("G");    //Reserve Result: 3.1415926
(P)Percent:string str2=("P");                   //Reserve Results: 314.16%
(E)Scientific:string str2=("E");                 //Reserve Result E: 3.141593E+000
(C)Currency:string str2=("C");                //reserve result:¥3.14

C# Double By Valid Number ToString

Convert double to characters that n significant numbers

I looked for various posts including searching for ‘significant digits’ in Microsoft documentation; the closest one is ToString("Gx")

But it returns a string that is no greater than this x-valid bit, for example

double a=1.2;
string s=("G3");

Get 1.2 instead of 1.20

So I wrote a function

        string DoubleToStringSignificantDigits(double a, int SignificantDigits)
        {
            string formaterG = 'G' + ("N0");
            string strResult = (formaterG);
            int resultLength = SignificantDigits;
            if (('-') >= 0) resultLength++;
            if (('.') >= 0) resultLength++;
            if ((a) < 1) resultLength++; //The absolute value is less than 1, and an integer 0 is not considered a valid bit            if ( < resultLength)
            {
                if (('.') < 0)
                {
                    strResult += '.';
                    resultLength++;
        }
                strResult = (resultLength, '0');
            }
            return (strResult);
         }

result

double[] x = new double[] { 100, 99, 12.12, 1.1234, 1.2, 0.2, 0.12345 , -0.2, -1.2, -123};
Convert
DoubleToStringSignificantDigits(x[i], 3)
get
100
99.0
12.1
1.12
0.200
0.123
-0.200
-1.20
-123

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.