How to set nice float value using Apache POI?

隐身守侯 提交于 2019-12-13 17:09:37

问题


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());

回答1:


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("#.#"));



回答2:


There's no reason to voluntarily limit the precision of your desired value by using a float. There's also no reason for using BigDecimal if all you need is a float.

Because 5.2 can't be represented exactly as a binary number, the closest float to the true "5.2" value is 5.19999980926513. If you need the cell to be numeric, you can use a double which has more precision. Besides, the setCellValue method is overloaded to take a double, not a float.

Your line in question:

worksheet.getRow(i + 1).getCell(0).setCellValue(new BigDecimal("5.2").floatValue());

... can be replaced with something simpler:

worksheet.getRow(i + 1).getCell(0).setCellValue(5.2);

The double value 5.2 is much closer to the "true" 5.2 value than the float value 5.2f that you get with the float literal 5.2f or from new BigDecimal("5.2").floatValue(). You will see 5.2 in Excel, in the actual cell and in the bar that shows the actual cell value. You don't even need to set the data format.

If you are required to use BigDecimal, maybe because you get a BigDecimal from somewhere else, and you simplified your code example here with new BigDecimal("5.2"), then at least call doubleValue(), and you can still set the cell value with a double:

worksheet.getRow(i + 1).getCell(0).setCellValue(new BigDecimal("5.2").doubleValue());



回答3:


you can use BigDecimal.setScale simple example

 BigDecimal a = BigDecimal.valueOf(5.165);
    BigDecimal roundOff = a.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    System.out.println(roundOff);

output

5.2

This is another way

double d = 5.165;
DecimalFormat f = new DecimalFormat("##.0");
System.out.println(f.format(d));

output 5.2




回答4:


You can use toPlainString() instead of floatValue()

new BigDecimal("5.2").toPlainString()

Edit:

new BigDecimal("5.2").setScale(2).floatValue()


来源:https://stackoverflow.com/questions/19332944/how-to-set-nice-float-value-using-apache-poi

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