How to display just first 2 decimals unequal to 0

前端 未结 4 1440
甜味超标
甜味超标 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:23

    My solution would be to convert the number to a string. Search for the ".", then count zeroes till you find a non-zero digit, then take two digits.

    It's not an elegant solution, but I think it will give you consistent results.

    0 讨论(0)
  • 2021-01-18 11:29

    There is no built in formatting for that.

    You can get the fraction part of the number and count how many zeroes there are until you get two digits, and put together the format from that. Example:

    double number = 1.0000533535;
    
    double i = Math.Floor(number);
    double f = number % 1.0;
    
    int cnt = -2;
    while (f < 10) {
      f *= 10;
      cnt++;
    }
    
    Console.WriteLine("{0}.{1}{2:00}", i, new String('0', cnt), f);
    

    Output:

    1.000053
    

    Note: The given code only works if there actually is a fractional part of the number, and not for negative numbers. You need to add checks for that if you need to support those cases.

    0 讨论(0)
  • 2021-01-18 11:29

    You can use this trick:

    int d, whole;
    double number = 0.00045578;
    string format;
    whole = (int)number;
    d = 1;
    format = "0.0";
    while (Math.Floor(number * Math.Pow(10, d)) / Math.Pow(10, d) == whole)
    {
        d++;
        format += "0";
    }
    format += "0";
    Console.WriteLine(number.ToString(format));
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题