向上舍入小数C#中的计算问题 [英] Calculation problem in round up decimals C#

查看:110
本文介绍了向上舍入小数C#中的计算问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

问题可能听起来有点愚蠢,但我在这里遇到了计算方案。



那里是不是。我将它除以否。然后再将它乘以相同的no。但我没有完全相同的没有。十进制值不同。任何人都可以告诉我一个问题的解决方法。

这是代码

Round1 Round2 有.00001差异。





static void Main(string [] args)

{

decimal ab = new decimal();

ab =(decimal)4.444445;

decimal Round1 = Math.Round(ab,5);

十进制c = ab / 3;

十进制d = c * 3;

十进制Round2 = Math.Round(d,5);

}

解决方案

请看我对这个问题的评论。



我会建议以下内容:永远不会解决任何问题。它没有任何意义,但可能会影响计算的准确性。有些情况下,在计算步骤中累积误差会导致误差远大于您所需的精度。根本不会对任何计算进行舍入。



相反,仅当您以字符串形式表示最终数据时才对数据进行舍入,例如,当您在屏幕上显示时或存储在文本文件中。在此步骤中,您仍然不需要舍入,因为它已经在字符串格式化中实现。换句话说,减少舍入问题到格式问题。请参阅:

https ://msdn.microsoft.com/en-us/library/system.double.tostring%28v=vs.110%29.aspx [ ^ ],

< a href =https://msdn.microsoft.com/en-us/library/kfsatb94%28v=vs.110%29.aspx> https://msdn.microsoft.com/en-us/library/kfsatb94 %28v = vs.110%29.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/dwhawy9k(v = vs.110).aspx [ ^ ],

HTTPS://msdn.micr osoft.com/en-us/library/0c899ak8(v=vs.110).aspx [ ^ ]。



-SA

Hi all,
The question might sound a bit dumb, but I have been caught in a calculation scenario here.

There is a no. I divide it by a no. then again multiply it by same no. but I do not get exactly the same no. Decimal values are different. Can anyone please tell me a workaround of the problem.
Here is the code
Round1 and Round2 are having .00001 difference.


static void Main(string[] args)
{
decimal ab = new decimal();
ab = (decimal)4.444445;
decimal Round1 = Math.Round(ab,5);
decimal c = ab / 3;
decimal d = c * 3;
decimal Round2=Math.Round(d,5);
}

解决方案

Please see my comment to the question.

I would advise the following: never ever round anything up. It just makes no sense, but can compromise the accuracy of calculations. There are cases when rounding error accumulate during calculation steps resulting in the error much greater than your required accuracy. Simply never round any calculations at all.

Instead, round up data only when you represent the final data in the string form, for example, when you show it on screen or store in a text file. At this step, you still don't need rounding itself, because it is already implemented in string formatting. In other words, reduce rounding problem to the formatting problem. Please see:
https://msdn.microsoft.com/en-us/library/system.double.tostring%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/kfsatb94%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx[^],
https://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx[^].

—SA


这篇关于向上舍入小数C#中的计算问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆