Rounding down to 2 decimal places in c#

前端 未结 7 2233
渐次进展
渐次进展 2020-12-03 10:07

How can I multiply two decimals and round the result down to 2 decimal places?

For example if the equation is 41.75 x 0.1 the result will be 4.175. If I do this in c

相关标签:
7条回答
  • 2020-12-03 10:33

    I've found that the best method is to use strings; the binary vagaries of Math tend to get things wrong, otherwise. One waits for .Net 5.0 to make this fact obsolete. No decimal places is a special case: you can use Math.Floor for that. Otherwise, we ToString the number with one more decimal place than is required, then parse that without its last digit to get the answer:

    /// <summary>
    /// Truncates a Double to the given number of decimals without rounding
    /// </summary>
    /// <param name="D">The Double</param>
    /// <param name="Precision">(optional) The number of Decimals</param>
    /// <returns>The truncated number</returns>
    public static double RoundDown(this double D, int Precision = 0)
    {
      if (Precision <= 0) return Math.Floor(D);
      string S = D.ToString("0." + new string('0', Precision + 1));
      return double.Parse(S.Substring(0, S.Length - 1));
    }
    
    0 讨论(0)
提交回复
热议问题