【问题标题】:How to round decimal value in c#?如何在c#中舍入十进制值?
【发布时间】:2013-11-28 07:16:55
【问题描述】:

我正在计算十进制的小值,预期结果是 = 345.00 但得到的结果是 = 345.0000

我的代码是decimal temp= 6900 * ( 5 / 100);

temp = 345.0000 如何舍入?我想显示 345.00 ?我的错误是什么? 我也试过这个代码Math.Round(tempdiscountprice, 2);,但它在这里不起作用。帮帮我

【问题讨论】:

  • 看起来是显示/显示不四舍五入的问题。
  • 谢谢guyz,我知道了,我使用了这个代码temp.ToString("N2")

标签: c# winforms gridview


【解决方案1】:

我不认为你在展示你的真实代码。以下将给出结果 0,因为 (5 / 100) 是使用整数算术计算的:

decimal temp = 6900 * (5 / 100);
Console.WriteLine(temp.ToString()); // result is 0

如果你使用十进制,你会得到如下:

decimal temp = 6900 * (5M / 100);
Console.WriteLine(temp.ToString()); // result is 345.00

但是十进制类型确实保留了尾随零:

decimal temp = 6900 * (5.0000M / 100);
Console.WriteLine(temp.ToString()); // result is 345.0000

像这样保留尾随零是 .NET 1.1 中引入的,以更严格地符合 ECMA CLI 规范。

但是没有什么可以阻止你用两位小数格式化输出,例如:

decimal temp = 6900 * (5.0000M / 100);
Console.WriteLine(temp.ToString("N2")); // result is 345.00

【讨论】:

  • 嗨,乔,我试过 temp.ToString("N2") 工作正常谢谢。我的原始代码是 price = 6900.00 & Tax = 5.00。
【解决方案2】:

正如user2864740 上面指出的那样,问题不在于您的舍入,而在于将值显示为字符串。试试:

 decimal temp = 345.0000m;
 String.Format("{0:0.00}", temp)

【讨论】:

    【解决方案3】:

    我认为您向我们展示了错误的代码,因为这不会得到 345.00345.0000 的结果。它总是得到0

    你的temp 应该是0,因为既然你做了integer division,你的5 / 100 总是0。这就是为什么你的temp 将是6900 * 0 然后它将是0

    如果您向我们展示正确的代码,您的问题看起来像 showing 问题而不是 rounding 问题。

    如果你想把你的数字格式化为字符串,看看;

    【讨论】:

      猜你喜欢
      • 2011-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多