DataColumn表达式除以零 [英] DataColumn Expression Divide By Zero

查看:178
本文介绍了DataColumn表达式除以零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用基本的.net DataColumns和相关的Expression属性。



我有一个应用程序,可以让用户定义从数据库表中选择哪些列。他们还可以添加在数据列上执行表达式的其他列,从而产生一个自定义的信息网格。



我遇到的问题是当它们有一个计算列时的(C2 / C3)* 100,其中C2和C3是数据列,C3的值为零。旧的除以零问题。



简单的答案是将表达式转换为IIF(C3 = 0,0(C2 / C3)* 100 ),但是我们不希望用户知道这样做,在编译时我不知道定义了哪些列。所以我必须以编程方式确定在分区中使用哪些列来构造IIF子句。



如果发生除以零错误,是否有另一种方法不会抛出错误并将结果替换为0?

解决方案

好的,我找到了一种方法。关键是对列类型使用Double而不是Decimal。在上面的例子中,C3应该是Double。这将导致无穷大的结果,可以对整个表达式进行评估。



例如。
IIF(CONVERT(([C4] / [C3])* 100,'System.String')='NaN'OR CONVERT(([C4] / [C3])* 100,'System.String' )='无穷大'OR CONVERT(([C4] / [C3])* 100,'System.String')='-Infinity',0,([C4] / [C3])* 100)



小数似乎没有提供无限期选项。


I'm using basic .net DataColumns and the associated Expression property.

I have an application which lets users define which columns to select from a database table. They can also add other columns which perform expressions on the data columns resulting in a custom grid of information.

The problem I have is when they have a calculation column along the lines of "(C2/C3)*100" where C2 and C3 are data columns and the value for C3 is zero. The old "divide by zero" issue.

The simple answer would be to convert the expression to "IIF(C3 = 0, 0, (C2/C3)*100)", however we don't expect the user to know to do that and at compile time I don't know what columns are defined. So I would have to programmatically determine which columns are being used in a division in order to construct the IIF clause. That could get quite tricky.

Is there another way to not throw an error and replace the result with 0 if a "Divide By Zero" error occurs?

解决方案

Ok, I found a way. The key is to use Double and not Decimal for the column type, e.g. in the example above C3 should be a Double. This will result in a result of Infinity instead, which can be evaluated against using the expression as a whole.

E.g. IIF(CONVERT(([C4] / [C3] )*100, 'System.String') = 'NaN' OR CONVERT(([C4] / [C3] )*100, 'System.String') = 'Infinity' OR CONVERT(([C4] / [C3] )*100, 'System.String') = '-Infinity', 0, ([C4] / [C3] )*100)

Decimal it seems doesn't provide that Infinity option.

这篇关于DataColumn表达式除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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