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

后端 未结 6 1364

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 15:56

    ToString() doesn't do it. You have to add extra code. The other answers show math approaches, my approach below is kind of outside-the-box.

    string result = value.ToString();
    Console.WriteLine("{0}", result.Substring(0, result.LastIndexOf('.') + 2));
    

    This is a fairly simple brute force approach, but it does the trick when the decimal is a '.'. Here's an extension method to ease the pain (and deals with the decimal point).

    public static class Extensions
    {
        public static string ToStringNoTruncate(this double me, int decimalplaces = 1)
        {
            string result = me.ToString();
            char dec = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
            return result.Substring(0, result.LastIndexOf(dec) + decimalplaces + 1);
        }
    }
    

提交回复
热议问题