Skip to content

Commit 9c8e4e3

Browse files
committed
#518 - improved handling of decimals in Concat operations during calculation
1 parent 5ed13c2 commit 9c8e4e3

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

src/EPPlus/FormulaParsing/Excel/Operators/Operator.cs

+14-2
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,18 @@ public static IOperator Exp
198198
}
199199
}
200200

201+
private static string CompileResultToString(CompileResult c)
202+
{
203+
if(c != null && c.IsNumeric)
204+
{
205+
if(c.ResultNumeric is double d)
206+
{
207+
return d.ToString("G15");
208+
}
209+
}
210+
return c.ResultValue.ToString();
211+
}
212+
201213
public static IOperator Concat
202214
{
203215
get
@@ -206,8 +218,8 @@ public static IOperator Concat
206218
{
207219
l = l ?? new CompileResult(string.Empty, DataType.String);
208220
r = r ?? new CompileResult(string.Empty, DataType.String);
209-
var lStr = l.Result != null ? l.ResultValue.ToString() : string.Empty;
210-
var rStr = r.Result != null ? r.ResultValue.ToString() : string.Empty;
221+
var lStr = l.Result != null ? CompileResultToString(l) : string.Empty;
222+
var rStr = r.Result != null ? CompileResultToString(r) : string.Empty;
211223
return new CompileResult(string.Concat(lStr, rStr), DataType.String);
212224
});
213225
}

src/EPPlus/FormulaParsing/ExpressionGraph/ExpressionConverter.cs

+10-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,16 @@ public class ExpressionConverter : IExpressionConverter
2323
public StringExpression ToStringExpression(Expression expression)
2424
{
2525
var result = expression.Compile();
26-
var newExp = new StringExpression(result.Result.ToString());
26+
string toString;
27+
if(result.DataType == DataType.Decimal)
28+
{
29+
toString = result.ResultNumeric.ToString("G15");
30+
}
31+
else
32+
{
33+
toString = result.Result.ToString();
34+
}
35+
var newExp = new StringExpression(toString);
2736
newExp.Operator = expression.Operator;
2837
return newExp;
2938
}

src/EPPlusTest/FormulaParsing/IntegrationTests/OperatorsTests.cs

+10
Original file line numberDiff line numberDiff line change
@@ -59,5 +59,15 @@ public void DivByZeroShouldReturnError()
5959
var result = _ws.Calculate("10/0 + 3");
6060
Assert.AreEqual(DivByZero, result);
6161
}
62+
63+
[TestMethod]
64+
public void ConcatShouldUseFormatG15()
65+
{
66+
var result = _ws.Calculate("14.000000000000002 & \"%\"");
67+
Assert.AreEqual("14%", result);
68+
69+
result = _ws.Calculate("\"%\" & 14.000000000000002");
70+
Assert.AreEqual("%14", result);
71+
}
6272
}
6373
}

0 commit comments

Comments
 (0)