Values of excel field is getting 3.0E9 where I need 3000000000 when trying to parse

喜夏-厌秋 提交于 2019-12-25 05:13:33

问题


i have an excel to upload which has a column material id.That column contains alphanumeric values,But when i am trying to upload this file value the uploaded column in the jsp page is taking an unexpected E and also taking decimal of that number i am using apache POI to parse the excel.Here i have done so far

while(rowIterator.hasNext()) {
                boolean isValidentry=true;
                System.out.println("Row number =" + (i+1));
                Row row = rowIterator.next();
                CategoryObject categoryObject = new CategoryObject();
                categoryObject.setCode("");
                if(row.getCell(0)!=null && !"".equals(row.getCell(0).toString().trim())){       //Part Number
                    System.out.println("Get Cell 0 >>>>" +row.getCell(0).toString());
                    categoryObject.setCode(row.getCell(0).toString().trim());

The problem is that I'm getting 3.0E9 where I need 3000000000.

categoryObject.setCode is taken as String field.This column is responsible for the material id.


回答1:


Numbers in Excel are (except for a few edge cases) stored as floating point numbers. Large floating point numbers in Java, when formatted as a string, are printed in Scientific notation

Assuming what you really wanted was "give me a string that looks like what Excel shows for this cell", then do not call cell.toString(). This will not give you what you want in most cases

Instead, you need to use the DataFormatter class, which provides methods which read the Excel format rules applied to a cell, then re-creates (as best it can) those in Java

Your code should be:

DataFormatter fmt = new DataFormatter();
for (Row row : sheet) {
     int rowNumber = row.getRowNum() + 1;
     System.out.println("Row number =" + rowNumber);
     CategoryObject categoryObject = new CategoryObject();
     categoryObject.setCode("");

     Cell cell = row.getcell(0, Row.RETURN_BLANK_AS_NULL);
     if(cell!=null) {
          String cellValue = fmt.formatCellValue(cell);
          if (! cellValue.trim().isEmpty()) {
             System.out.println("Get Cell 0 >>>>" + cellValue);
             categoryObject.setCode(cellValue);
          }
     }
 }

You may notice I've also fixed a bunch of other stuff as well....!




回答2:


use BigDecimal to prevent E notation from number

BigDecimal bDec = new BigDecimal("3.0E9");
System.out.println(bDec.toPlainString());

output:

3000000000

running example



来源:https://stackoverflow.com/questions/25397377/values-of-excel-field-is-getting-3-0e9-where-i-need-3000000000-when-trying-to-pa

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