【问题标题】:C# decimal places with integer operators带有整数运算符的 C# 小数位
【发布时间】:2010-05-20 14:26:53
【问题描述】:

所以我有这个代码:

p.Value = 1;
decimal avg = p.Value * 100 / 10000;
string prntout = p.Key + " : " + avg.ToString();
Console.WriteLine(prntout);

但是程序打印出 0,而不是 0.01。 p.Value 是一个整数。我该如何解决?

【问题讨论】:

    标签: c# string format decimal int


    【解决方案1】:

    将其中一个文字更改为小数:

    decimal avg = p.Value * 100m / 10000;
    

    现在,解释一下为什么会这样:

    让我们一次处理原始行一个操作,用 1 代替 p.Value:

    decimal avg = 1 * 100 / 10000; // int multiplication
    decimal avg = 100 / 10000; // int division, remainder tossed out
    decimal avg = (decimal) 0; // implicit cast
    

    通过将 100 更改为 100m,现在是:

    decimal avg = 1 * 100m / 10000; // decimal multiplication
    decimal avg = 100m / 10000; // decimal division
    decimal avg = 0.01m;
    

    【讨论】:

    • 旁注:Decimal 的字面量类型代码是m,大概是为了钱。
    【解决方案2】:

    表达式p.Value * 100 / 10000 仅使用整数类型,因此根据integer division 规则进行计算。

    将一个(或多个)参数更改为小数,它将按预期执行:

    p.Value * 100 / 10000m
    

    【讨论】:

      【解决方案3】:

      尝试改变这个:

      decimal avg = p.Value * 100 / 10000;
      

      decimal avg = Convert.ToDecimal(p.Value) * 100.0 / 10000.0;
      

      您以前的版本使用所有整数。

      【讨论】:

        【解决方案4】:

        如果 P.Value 是一个整数,你可能会丢失这一行的分数:

        十进制平均值 = p.Value * 100 / 10000;

        所以你可以这样做:

        十进制平均值 = (十进制)P.Value * 100 / 10000;

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 2014-12-02
          • 2015-05-30
          • 1970-01-01
          • 1970-01-01
          • 2023-02-04
          • 2019-10-21
          • 2014-05-26
          • 2013-02-16
          • 2017-12-05
          相关资源
          最近更新 更多