Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove decimals after a numeric value in java

Hi I have a excel file reading application which reads every cell in the file.

whenever a cell contains a numeric value the app is treating it a numeric cell.

For example the cell contains (40002547) the application will treat this as numeric cell. I cab get the value by using this code:

SONum = String.valueOf(cellSONum.getNumericCellValue());

Well that works fine. My Problem is it appends decimal at the end of the string. it will be (40002547.0). I need it to be as is. Thanks in advance

like image 309
Bimbz Avatar asked Dec 02 '22 18:12

Bimbz


2 Answers

It's because cellSONum.getNumericCellValue() is returning a floating point type. If you force it to an integer before calling valueOf(), you should get the string representation in an integral form, if indeed that's what you want for all possibilities:

SONum = String.valueOf((int)cellSONum.getNumericCellValue());

You can see this in the following code:

class Test {
    public static void main(String[]args) {
        double d = 1234;
        System.out.println(String.valueOf(d));
        System.out.println(String.valueOf((int)d));
    }
}

which outputs:

1234.0
1234

However, if you want to just get rid of .0 at the end of any string but allow non-integral values to survive, you can just remove the trailing text yourself:

class Test {
    public static void main(String[]args) {
        double d1 = 1234;
        double d2 = 1234.567;
        System.out.println(String.valueOf(d1).replaceFirst("\\.0+$", ""));
        System.out.println(String.valueOf(d2).replaceFirst("\\.0+$", ""));
    }
}

That snippet outputs:

1234
1234.567
like image 176
paxdiablo Avatar answered Dec 10 '22 12:12

paxdiablo


Try with split().

         SONum = String.valueOf(cellSONum.getNumericCellValue());
         SONum  = SONum.split("\\.")[0];

When you split 40002547.0 with . ,the split function returns two parts and the first one you need.

like image 44
Suresh Atta Avatar answered Dec 10 '22 12:12

Suresh Atta