【问题标题】:Math.Round decimal in Visual Studio C# not rounding [closed]Visual Studio C# 中的 Math.Round 小数不舍入 [关闭]
【发布时间】:2021-01-23 01:44:21
【问题描述】:

我希望我的 calc 返回两位小数。 我用谷歌搜索并找到了 Math.Round 函数。 我将它应用于我的代码的几个地方,即在声明变量之后、返回语句之前、计算行之前和计算行之后,但得到 $251.333333333333 作为我的结果。 我的代码如下所示:

public decimal finalCalc()
    {
        decimal calcNumber3;
        decimal g = firstPartofCalc();
        decimal h = secondPartofCalc();

        if (rbMonthlyPay.Checked)
        {
            Math.Round(calcNumber3 = (((g + h) * 52) / 12), 2) ;
        }
        else
        {
            calcNumber3 = g + h;
        }
        return calcNumber3;
    }

Calcs 1 和 2 返回十进制结果。我知道还有其他几种方法可以获得相同的结果,包括将结果作为字符串返回。但是,作为编码方面的新手,我真的很想了解为什么这不起作用。

TIA 薇姬

【问题讨论】:

  • Math.Round(calcNumber3 = ??
  • 你在用哪本书来学习 C#?
  • 发生了什么,你正在执行 integer division 这可能会给你带来奇怪的结果,试试(((g + h) * 52) / (decimal)12)(((g + h) * 52) / 12m)
  • 此外:整数除法将返回两个操作数x / y向零舍入,商可以认为是整数部分一个部门......这就是为什么我们不能拥有美好的东西......
  • 重要的是要注意Math.Round(anyVariable = ...)anyVariable = Math.Round(...) 有很大的不同。您没有使用返回值。

标签: c# visual-studio rounding


【解决方案1】:

您没有正确地将计算值分配给 calcNumber3,请将其更改为:

calcNumber3 = Math.Round((((g + h) * 52) / 12), 2) ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    相关资源
    最近更新 更多