首页 > 解决方案 > 复利计算

问题描述

我有这个 C# 代码,它每年计算复利加本金。

static void CompoundInterest(double principal, double interestRate, double years, double annualCompound)
    {
        var total = 0.0;
        for (int t = 1; t < years + 1; t++)
        {
            total = principal * Math.Pow((1 + interestRate / annualCompound),
                                     (annualCompound * t));
            Console.Write("Your Total for Year {0} "
                        + "is {1}. \n", t, total);
        }
    }

当我用

 CompoundInterest(1000, 0.05, 3, 12);

输出是

Your Total for Year 1 is 1051.161897881733.
Your Total for Year 2 is 1104.941335558327.
Your Total for Year 3 is 1161.4722313334678.

我应该如何准确地四舍五入?另一个问题是Math.Pow用途double,但在财务计算中,我们需要decimal. 我该如何解决?后转换成十进制Math.Pow

标签: c#

解决方案


如果您愿意,可以直接将双精度数转换为小数

decimal decimalTotal = (decimal)total;

至于舍入,有一个内置函数 Math.Round,它采用多种数字格式。它有一个重载来指定你想要多少个小数点。

decimal roundedDecimal = Math.Round(decimalTotal, 2);

推荐阅读