C# How to format a double to one decimal place without rounding

后端 未结 6 1368

I need to format a double value to one decimal place without it rounding.

double value = 3.984568438706
string result = \"\";

What I have tried

6条回答
  •  名媛妹妹
    2021-02-18 16:08

    I would make a utility method to handle this:

    static double Truncate(double value, int digits)
    {
        double mult = System.Math.Pow(10.0, digits);
        return System.Math.Truncate(value * mult) / mult;
    }
    

    You could then do:

    result = Truncate(value, 1).ToString("##.#", System.Globalization.CultureInfo.InvariantCulture) + "%"; 
    

    Note that you may also want Math.Floor instead of truncate - but it depends on how you want negative values handled.

提交回复
热议问题