c# - 复利计算
问题描述
我有这个 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
?
解决方案
如果您愿意,可以直接将双精度数转换为小数
decimal decimalTotal = (decimal)total;
至于舍入,有一个内置函数 Math.Round,它采用多种数字格式。它有一个重载来指定你想要多少个小数点。
decimal roundedDecimal = Math.Round(decimalTotal, 2);
推荐阅读
- javascript - 如何通过 App 直接在 Google Play 上评价我的应用
- r - 分类尺度上 geom_point 的 position_dodge 的垂直等效项
- amcharts - AmCharts (type = stock) 自定义 zoomToIndexes(start, end) 不起作用
- c# - 错误 Microsoft.SqlServer.Management.Smo.SqlSmoObject.get_ServerVersion()'。'
- python - 如何从命令行导入我的 django 应用程序模型?
- mysql - 将每月成本除以一年中剩余的月数并将其拆分为多行
- r - 如何在循环中重复调用 R 并检索结果以在 SAS 中进一步处理
- python - Jupyter Notebook Azure 机器学习实验
- python - 如何读取 div id
- .net - EPPlus 计算方法在 Matlab 中不可见或无法访问