How to display just first 2 decimals unequal to 0

前端 未结 4 1439
甜味超标
甜味超标 2021-01-18 10:52

How can I display the number with just the 2 not=zero decimals?

Example:

For 0.00045578 I want 0.00045 and for 1.0000533535 I want 1.000053

4条回答
  •  广开言路
    2021-01-18 11:40

    Try this function, using parsing to find the # of fractional digits rather than looking for zeros (it works for negative #s as well):

    private static string GetTwoFractionalDigitString(double input)
    {
        // Parse exponential-notation string to find exponent (e.g. 1.2E-004)
        double absValue = Math.Abs(input);
        double fraction = (absValue - Math.Floor(absValue));
        string s1 = fraction.ToString("E1");
        // parse exponent peice (starting at 6th character)
        int exponent = int.Parse(s1.Substring(5)) + 1;
    
        string s = input.ToString("F" + exponent.ToString());
    
        return s;
    }
    

提交回复
热议问题