Values of excel field is getting 3.0E9 where I nee

2019-09-06 15:36发布

问题:

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