Search code examples
javafloating-pointapache-poicellxls

How to set nice float value using Apache POI?


I'm trying to set a cell value to a nice float value. I want to set cell value to 5.2, but I get 5.1999998093 instead. What would be a solution for this?

Workbook workbook = new HSSFWorkbook();
Sheet worksheet = workbook.createSheet();
CellStyle style = workbook.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.0"));

int i = 0;
worksheet.createRow(i + 1);
worksheet.getRow(i + 1).createCell(0).setCellStyle(style);
worksheet.getRow(i + 1).getCell(0).setCellValue(new BigDecimal("5.2").floatValue());

Solution

  • You guys didn't understand what was my problem well. A solution was to change data format:

    DataFormat format = workbook.createDataFormat();
    style.setDataFormat(format.getFormat("#.#"));