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("#.#"));
Pregunta
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());
Solución
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("#.#"));
Otros consejos
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());
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
You can use toPlainString()
instead of floatValue()
new BigDecimal("5.2").toPlainString()
Edit:
new BigDecimal("5.2").setScale(2).floatValue()