0

I have a list of long integers in a text file. I want to read those numbers to long arraylist in java. Out numbers are stored in the file:

2.2278e+08
1.2339e+09
6.1868e+08

My code to read those long numbers are the following:

for (String line : Files.readAllLines(Paths.get("ids.txt"))) {
                    ids.add(Long.parseLong(line, 10));
                    System.out.println(Double.valueOf(line).longValue());
}

However I got the following exceptions:

Exception in thread "main" java.lang.NumberFormatException: For input string: "2.2278e+08"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at twittertrendsetters.TwitterTrendSetters.main(TwitterTrendSetters.java:580)

Java Result: 1

How can I convert 2.2278e+08 to the long integer number 22278111 which is in fact

Jose Ramon
  • 5,572
  • 25
  • 76
  • 152

1 Answers1

2

The thing is that numbers like 2.2278e+08, 1.2339e+09 and 6.1868e+08 are in floating-point notation and therefore cannot be parsed as long numbers directly.

However you could parse them as double values doing something like

long l = Double.valueOf("2.2278e+08").longValue();

Of course this departs from the assumption that you know that all these numbers are integers and that they fit in the size of a long value. Otherwise you may need to resort to other techniques.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
  • 1
    As a side note, `new BigDecimal("2.2278e+08").longValue()` would also work, but the result should be the same. – Tom Jan 29 '15 at 12:56