How to display just first 2 decimals unequal to 0

前端 未结 4 1459
甜味超标
甜味超标 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: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));
    

提交回复
热议问题