Rounding discrepancy of Decimals in Excel vs. EPPlus
Issue
I have the following decimal value: 53,9549999999999999 and would like to format it to have two decimal points in Excel.
To accomplish this task, I use the following code:
decimal d = 53.9549999999999999M;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
FileInfo file = new FileInfo(@"E:\unhandlyDecimal.xlsx");
using (ExcelPackage ep = new ExcelPackage(file))
{
ExcelWorksheet sheet = ep.Workbook.Worksheets.Add("Demo");
sheet.Cells["A1"].Style.Numberformat.Format = "#,##0.00";
sheet.Cells["A1"].Value = d;
Console.WriteLine($"1 Value: {sheet.Cells["A1"].Value}"); // 1 Value: 53.9549999999999999
Console.WriteLine($"1 Round: {Math.Round(d, 2)}"); // 1 Round: 53.95
Console.WriteLine($"1 Text: {sheet.Cells["A1"].Text}"); // 1 Text: 53.96
ep.Save();
}
using (ExcelPackage ep = new ExcelPackage(file))
{
ExcelWorksheet sheet = ep.Workbook.Worksheets["Demo"];
Console.WriteLine($"2 Value: {sheet.Cells["A1"].Value}"); // 2 Value: 53.955
Console.WriteLine($"2 Text: {sheet.Cells["A1"].Text}"); // 2 Text: 53.96
}
After saving the workbook and loading it again, the decimal value has been truncated to just 53.955.
Now, I know that Excel has limits to its precision. When setting my ugly decimal value in Excel directly or through Interops (which I am migrating from) Excel saves the value as 53,9549999999999 and rounds it correctly to 53.95 and not 53.96.
Is this intentional?
Thanks in advance!
-trienow
Versions
| Entity | Version |
|---|---|
| Excel | 2108 (Build 14326.20404) |
| EPPlus | 5.7.5 |
| .NET Framework | 4.7.2 |
This is because you are using a decimal. EPPlus and Excel works with doubles, that has a lower precision.
EPPlus will convert the decimal to a double in the Text property...
var d = 53.9549999999999999M;
var dbl = Convert.ToDouble(d);
// dbl will be converted to 53.955
You will have to truncate the decimals to a size that fits in a double, otherwise you will get this behavior.
I appreciate your quick reply. I was not aware of that. Thank you.