2

I want to read data from Excel - only numbers so I can compare it later, I go in a loop and I have code like this:

int type = cell.getCellType();
    switch(type){
    case 0:
        int value = (int)cell.getNumericCellValue();
    case 1:
        String temp = cell.getStringCellValue();
        int value = Integer.parseInt(temp);

    }

It's like this because sometimes data in Excel have numeric type, sometimes string type.

Now my questions. Is casting to int a good idea? If I have number 1.200 in a cell with type String so it's "1.200" how to convert it to int (or float if it's better)? What is the best way to do it?

All I need is - numbers (sometimes from String cell types) so I can compare it with numbers from another datasource.

1
  • 1
    Please also use the constants from Cell for "case 0" and "case 1", e.g. Cell.CELL_TYPE_NUMERIC and Cell.CELL_TYPE_STRING to avoid confusion Commented Aug 23, 2016 at 8:43

1 Answer 1

3

CellType.Numeric refers to cells whose contents contain integers, fractions or dates.

Therefore, if you are reading cells that can potentially have more than one specific numeric type then you will need to put in further work to narrow the classification.

getNumericCellValue() returns a double (assuming the cell is of type CellType.Numeric)

Casting this double to int will result in the decimal and all digits after being dropped. So 1.200 would become 1. Hence it is likely in your case that casting it as a float is better. If you want to ensure no loss in accuracy then don't cast at all; just save it as a double.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.