舍入和添加不起作用 [英] Rounding and Adding not working

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

问题描述

我有一个分割,回合和添加的表单。我得到了分割和舍入工作,但在尝试添加时我得到了这个错误:



I have a form that Divides, Rounds and Adds. I got the Dividing and Rounding working but when trying to Add I get this error:

Input string was not in a correct format.





在这一行:





On this line:

int d = Convert.ToInt32(TextBoxTHGDR.Text.Replace(",", ""));





这是完整的代码:





Here is the whole code behind:

protected void TextBoxTHG_TextChanged(object sender, EventArgs e)
        {
            int i = Convert.ToInt32(TextBoxTHG.Text.Replace(",", ""));
            TextBoxTHGDR.Text = Convert.ToString(i / 9.0);

            int a = Convert.ToInt32(TextBoxFTUG.Text.Replace(",", ""));
            int b = Convert.ToInt32(TextBoxFTG.Text.Replace(",", ""));
            int c = Convert.ToInt32(TextBoxTHUGDR.Text.Replace(",", ""));
            int d = Convert.ToInt32(TextBoxTHGDR.Text.Replace(",", ""));
            TextBoxT1234.Text = Convert.ToString(a + b + c + d);
            TextBoxTHGDR.Text = Math.Round(Convert.ToDouble(TextBoxTHGDR.Text), 2).ToString();
            TextBoxTHGDR.Text = string.Format("{0:0,0}", double.Parse(TextBoxTHGDR.Text));
}





发生了什么事情,当输入一个数字时,它会被分割,舍入和添加其他数字。如何阻止此错误发生?我错过了什么?



What is going on is that when a number is entered it is Divided, Rounded and Added with other numbers. How can I stop this error from happening? What did I miss?

推荐答案

首先,停止尝试使用Convert.Int32处理用户输入:改为使用int.TryParse。它有一个重载,允许数千个分隔符作为NumberStyles值:

https://msdn.microsoft.com/en-us/library/zf50za27%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 [ ^ ]
First off, stop trying to use Convert.Int32 to deal with user input: use int.TryParse instead. It has an overload which allows thousands separators as the NumberStyles value:
https://msdn.microsoft.com/en-us/library/zf50za27%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396[^]


该异常表示您尝试解析整数的字符串实际上并不包含有效整数。



问题可能是由于以下原因:



它可能包含额外空间。使用trim()函数删除不必要的sapces。

字符串格式不正确意味着它包含一些字母数字,字符或特殊字符。



当你的字符串只能保留0-9之间的值时,除非你抛出异常。



你可以使用int.TryParse()。但是,如果发生异常,您将得到0结果。

The exception means that the string you're trying to parse an integer from doesn't actually contain a valid integer.

The issue may be due to following reasons:

It may contains extra space. Use trim() function to delete unnecessary sapces.
String is not correct format means either it contains some alphanumeric, chars or special chars.

When your string should conatin only value from 0-9 except that it throw you exception.

You can use int.TryParse(). However if exception occurs you will get 0 as result.
int finalResult;
bool output;
string str = "";
output = int.TryParse(str, out finalResult); // Here you wil get 0 as result


这篇关于舍入和添加不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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