[英]Apache-POI - How do i round numbers like Excel does in Cell-Editor
I use the Apache-POI "XSSF and SAX Event API" for Importing Excel-Files. 我使用Apache-POI“ XSSF和SAX事件API”来导入Excel文件。
Im parsing Raw-Values with Apache-POI and want to ask, how can i round those Raw-Values exactly like the Excel-GUI does for the Cell-Editor. 我用Apache-POI解析原始值,并想问一下,如何像Excel-GUI对单元编辑器所做的那样完全舍入这些原始值。 Following example illustrates the problem:
以下示例说明了该问题:
Raw: 1.9210999999999999E-2 (value is stored like this in xlsx-file)
Edit: 1.9211% (user sees this value in excel cell-editor)
View: 1.92% (user sees this value in excel grid-overview)
Format: 0.00% (the cell-style)
How does Excel read the Raw-Value to the Edit-Value ? Excel如何将原始值读取为编辑值? How does Excel know that it needs to round to a fraction of 4 digits after the decimal-separator.
Excel如何知道它需要四舍五入到小数点分隔符后的四位数。 How can Apache POI help me to do it the same, so i can also use the Edit-Value (and not the View-Value) in my Excel-Import?
Apache POI如何帮助我做到这一点,因此我也可以在Excel导入中使用Edit-Value(而不是View-Value)?
I have seen a similar Ticket that covers how Excel does it: How does Excel successfully Rounds Floating numbers even though they are imprecise? 我看过一张类似的票证,其中涵盖了Excel的工作方式: 即使Excel不精确,Excel如何成功将其四舍五入?
In this Ticket i want to ask, how can Apache POI help me so i do not need to reinvent the wheel here, and implement Excels Algorithm. 在此故障单中,我想问一下,Apache POI如何为我提供帮助,因此我无需在这里重新发明轮子,也无需实施Excels算法。
Excel gets the double value according to IEEE 754 specification and then it rounds to 15 significant digits before displaying in the sheet. Excel根据IEEE 754规范获取双精度值,然后四舍五入为15个有效数字,然后在表格中显示。
To do the same one could using BigDecimal rounded according to the MathContext settings of 15 digits precision. 为此,可以使用BigDecimal根据15位精度的MathContext设置进行四舍五入。
import java.math.BigDecimal;
import java.math.MathContext;
class ReadLongNumbersAsExcel {
public static void main(String[] args) throws Exception{
String v = "1.921099999999999E-2";
double d = Double.parseDouble(v);
System.out.println("raw: " + v);
System.out.println("double: " + d);
BigDecimal bd = new BigDecimal(d);
v = bd.round(new MathContext(15)).toPlainString();
System.out.println("like Excel: " + v);
}
}
The %
case is a special case since Excel shows in this case not the value which was really stored but shows this value multiplied by 100 and followed by "%". %
情况是一种特殊情况,因为在这种情况下Excel不会显示实际存储的值,而是显示此值乘以100,然后再加上“%”。 So if you wants the same then do the same. 因此,如果您想要相同,请执行相同操作。 After getting the raw value rounded to 15 significant digits do multiplying with 100 and append a "%".
将原始值四舍五入到15个有效数字后,请乘以100,然后附加“%”。
But if the need is only getting the formatted value like in Excel, then see How to check a number in a string contains a date and exponential numbers while parsing excel file using apache event model in java 但是,如果仅需要像在Excel中那样获取格式值,则请参阅在Java中使用apache事件模型解析excel文件时 , 如何检查包含日期和指数数字的字符串中的数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.