Numerical values in Excel 2007 - representation vs storage in the underlying xml file

随声附和 提交于 2021-02-10 09:36:15

问题


This question is related to .NET and OpenXml.

I've already gone through the following article, it has good explanation, but not an answer to my question: Inconsistent visualization of numerical values in Excel 2007 vs the underlying xml file

In my application, user is uploading an Excel (.xls/.xlsx) and I'm parsing using OpenXML SDK.

Parsing works fine, except a few values. Excel is storing different values than entered in some of the scenarios. Following are some examples of what user entered vs what is stored in underlying xml:


+--------------------+-----------------------+--------------------+
| User Entered Value | Excel Displayed Value | Stored XML Value   |
+--------------------+-----------------------+--------------------+
| 4.1                | 4.1                   | 4.0999999999999996 |
+--------------------+-----------------------+--------------------+
| 4.4                | 4.4                   | 4.4000000000000004 |
+--------------------+-----------------------+--------------------+
| 19.99              | 19.99                 | 19.989999999999998 |
+--------------------+-----------------------+--------------------+

My problem comes when I'm parsing this excel in .NET using OpenXML. OpenXML reads these values as what is stored as XML values. So even though user entered 4.1, OpenXML reads it as 4.0999999999999996. Now as per the one of the validations I'm running on this excel, I need to check for the decimal points. I cannot really validate what user entered in this kind of a situation.

Any help is greatly appreciated !! Since OpenXml is an SDK provided by Microsoft, I haven't tried any other Excel readers, but any suggestions are welcomed.


回答1:


This is the correct way to represent data of floating point type. You can verify that by following code snippet.

Run following code,

string s = "4.0999999999999996";

Console.WriteLine(float.Parse(s)); 
// output 4.1

string s1 = "4.4000000000000004";

Console.WriteLine(float.Parse(s1)); 
// output 4.4

string s2 = "19.989999999999998";

Console.WriteLine(float.Parse(s2)); 
// output 19.99

So try to parse those values and you will get your expected true value as it is.



来源:https://stackoverflow.com/questions/28490218/numerical-values-in-excel-2007-representation-vs-storage-in-the-underlying-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!