我目前正在使用ncalc库做几次评估,并从中得到结果。
现在我发现了一个问题,如果我有一个"1,234.01“格式的价格,它将无法计算我的表达式。
我目前使用的解决方法是删除,,但我想知道是否有方法可以在不删除,的情况下评估一种货币,例如:
decimal price = 0;
if (!decimal.TryParse(iPrice.Text, out price))
{
MessageBox.Show("Price is not formatted correctly...");
return;
}
decimal currency = 0;
if (!decimal.TryParse(iCurrency.Text, out currency))
{
MessageBox.Show("Currency is not formatted correctly...");
return;
}
string formula = iFormula.Text.Replace("Price", price.ToString("n2")).Replace("Currency", currency.ToString("n2"));
Expression exp = new Expression(formula);
exp.Evaluate();评估失败是因为我的价格中的,,如果我删除它,它工作得很好。
公式示例:
(((Price+12,9)+((Price+12,9)*0,05)+(((Price+12,9)+((Price+12,9)*0,05))*0,029)+0,45)*Currency)根据请求进行堆栈跟踪:
NCalc.EvaluationException was unhandled
Message=mismatched input ',' expecting ')' at line 1:4
mismatched input ',' expecting ')' at line 1:20
mismatched input ',' expecting ')' at line 1:43
mismatched input ',' expecting ')' at line 1:59
missing EOF at ')' at line 1:77
Source=NCalc
StackTrace:
at NCalc.Expression.Evaluate()发布于 2012-07-02 14:21:24
你的问题对我来说仍然不清楚,但我怀疑你可以通过改变替换时使用的格式来解决这个问题。更改此设置:
string formula = iFormula.Text.Replace("Price", price.ToString("n2"))
.Replace("Currency", currency.ToString("n2"));要这样做:
string formula = iFormula.Text.Replace("Price", price.ToString("f2"))
.Replace("Currency", currency.ToString("f2"));它将使用“定点”格式而不是“数字”格式。你不会得到分组。请注意,分组不是数字本身的一部分-它是格式化数字的一部分。
顺便说一句,我还想显式地指定不变的区域性。
顺便说一句:我自己还没有使用过NCalc,但是如果它真的强迫您将表达式中的数值指定为文本,那听起来就很糟糕了。我期待着某种参数化(例如,根据大多数SQL提供程序),它应该可以消除所有这些问题。
发布于 2012-07-02 13:53:44
不能,十进制文字中不能有分隔符。编译器会将其与声明具有相同类型的多个变量相混淆,例如:
decimal price = 1m, tax = 234m; 然而,如果它是一个字符串,你可以这样解析它:
decimal price = Decimal.Parse("1,234.0", CultureInfo.InvariantCulture); 编辑:我上面的回答是针对问题的第一个版本中的代码样本。现在问题已经编辑好了:
可以使用Decimal.ToString(string format, IFormatProvider provider)方法重载控制十进制值的字符串表示形式。这允许您指定standard或custom格式的字符串。在您的示例中,听起来需要用点分隔两个十进制数字,并且没有组分隔符(没有逗号)。所以你可以说:
price.ToString("F2", CultureInfo.InvariantCulture) // ex. result: "1234.56"如果无论当前区域性如何,都需要点分隔符,则CultureInfo.InvariantCulture很重要。如果不指定,则输出可能是"1234,56“,这取决于当前的区域性(例如,对于像de-DE或FR-FR这样的欧洲区域性)。
https://stackoverflow.com/questions/11288304
复制相似问题