计算时舍入问题 [英] Rounding issue when calculating

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

问题描述

我有一个网页表单,可以通过文本框文本更改进行计算。我有一个代码,它将两个数字分开,并在另一个文本框中显示答案。然后将答案四舍五入并显示在文本框中。显示的答案不是正确的。这就是我所拥有的:



Textbox1 = 923



b = 120



Textbox3 =回答



这是计算:

I have a web form that does calculations by textbox text change. I have a code that divides two numbers and shows the answer in another textbox. The answer is then rounded and shown in the textbox. The answer shown is not rounded right. Here is what I have:

Textbox1 = 923

b = 120

Textbox3 = answer

Here is the calculation:

int a = Convert.ToInt32(Textbox1.Text);
int b = 120;
Textbox3.text = Convert.ToString(a / b);



Textbox3的答案是7.691666666666667

这是我的舍入代码:


Textbox3 answer is 7.691666666666667
Here is my rounding code:

Textbox3.Text = Math.Round(Convert.ToDouble(TextBoxNCCDR.Text), 2).ToString();



当答案四舍五入时,新答案是7.为什么不是8?如何将舍入舍入到最接近的整数?


When the answer is rounded the new answer is 7. Why is it not 8? How can I get the rounding to round to the nearest whole number?

推荐答案

因为它是整数运算 - 并且它对分数部分一无所知!

将所有 int 值更改为 double ,并且它将按预期执行:

Because it's integer arithmetic - and it doesn't know anything about fractional parts!
Change all your int values to double and it'lkl do what you expected:
double a = Convert.ToDouble(Textbox1.Text);
double b = 168;
Textbox3.text = (a / b).ToString();





BTW:做任何类型的标准方法到一个字符串是使用ToString方法而不是Convert.ToString - 每个类型实现它,你的类可以覆盖它以产生有意义的消息。



并且四舍五入很容易:Math.Ceiling会这样做:



BTW: The standard way to do any type to a string is to use the ToString method for the class rather than Convert.ToString - every type implements it, and your classes can override it to produce a meaningful message.

And rounding up is easy: Math.Ceiling will do it:

Console.WriteLine(Math.Ceiling(7.6916666666));

会给你8


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

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