Remove decimals after a numeric value in java

21,929

Solution 1

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

Solution 2

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.

Solution 3

If you want to be sure you are not cutting of any valid decimals, you can use regexp also:

String pattern = "\.0+"; // dot followed by any number of zeros
System.out.println(String.valueOf(cellSONum.getNumericCellValue()).replaceAll(pattern, "")); 

More on java regexp for example: http://www.vogella.com/articles/JavaRegularExpressions/article.html

Solution 4

As PaxDiablo also mentions, cellSONum.getNumericCellValue() returns a floating point.

You can cast this to Long or int to get rid of all behind the '.'

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

used as example:

String SONum = String.valueOf((new Double(0.5)).longValue());
Share:
21,929
Bimbz
Author by

Bimbz

Software Engineer at MSI-ECS Phils.

Updated on August 05, 2022

Comments

  • Bimbz
    Bimbz almost 2 years

    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