我有一个用户将修改的数据网格。一列存储Single preciion浮点数。当用户输入长于7位的数字时,该数字以科学计数法显示,并且与数字的比较变得非常不准确。我想警告用户,当这种情况发生时,该号码仅被存储为近似值。有没有办法确定何时将一个号码正确存储在一个号码中?截止值似乎约为7位数。除此之外还有其他任何事情。
答案 0 :(得分:2)
我认为您需要对每个单元格进行验证。
一步一步解释:
按设计者或代码将DataValidating事件添加到DataGridView:
dataGridView1.CellValidating+=dataGridView1_CellValidating;
检查您是否想要这样:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
double value = 0;
if (double.TryParse(e.FormattedValue.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out value))
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "";
// e.Cancel = false;
}
else
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "Bad Input Please Correct It !";
// e.Cancel = true; if you do this the datagrid dont let user go next row
}
}
如果你想要改变自己的价值,那么这一步也是如此:
也添加CellValidated事件:
dataGridView1.CellValidated+=dataGridView1_CellValidated;
并检查:
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1[e.ColumnIndex, e.RowIndex].Value == null)
return;
double value = 0;
if (double.TryParse(dataGridView1[e.ColumnIndex,e.RowIndex].Value.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out value))
{
dataGridView1[e.ColumnIndex, e.RowIndex].Value = Math.Round(value, 2).ToString().Replace("/",".");
}
}
注意:如果您希望在特殊单元格上执行这些操作,则每次进行单元格编辑时都会发生此事件。您可以为每列设置最大输入长度,以避免错误输入。
答案 1 :(得分:1)
您可以随时通过解析输入并将其转回string
来检查自己:
string s = "0.12345678";
return Single.Parse(s).ToString() == s;
答案 2 :(得分:1)
第二个你在float
或double
中存储任何数字,假设它不再100%准确,因为赔率不是。第二个你对数字执行任何操作,特别是如果它不是加/减,你可以相当确定某些错误。如果你想知道它们究竟有多少错误,那么你就开始进入一些相当复杂的数学。