2

I've googled around a bit but could not find examples to find a solution. Here is my problem:

String s = "100.000";
long l = Long.parseLong(s);

The 2nd line of code which tries to parse the string 's' into a long throws a NumberFormatException.

Is there a way around this? the problem is the string representing the decimal number is actually time in milliseconds so I cannot cast it to int because I lose precision.

temelm
  • 826
  • 4
  • 15
  • 34

7 Answers7

4

You could use a BigDecimal to handle the double parsing (without the risk of precision loss that you might get with Double.parseDouble()):

BigDecimal bd = new BigDecimal(s);
long value = bd.longValue();
assylias
  • 321,522
  • 82
  • 660
  • 783
4

as i don't know is your 100.000 equals 100 or 100 000 i think safest solution which i can recommend you will be:

NumberFormat nf = NumberFormat.getInstance();
Number number = nf.parse("100.000");
long l = number.longValue();
user902383
  • 8,420
  • 8
  • 43
  • 63
2

'long' is an integer type, so the String parse is rejected due to the decimal point. Selecting a more appropriate type may help, such as a double.

Kenogu Labz
  • 1,094
  • 1
  • 9
  • 20
  • http://stackoverflow.com/questions/888088/how-do-i-convert-a-string-to-double-in-java-using-a-specific-locale – Uncle Iroh Oct 26 '12 at 15:46
  • Yeah, I realized a bit late that this may be European notation. I may just delete this answer, as it seems others have covered the gamut of good possible solutions. – Kenogu Labz Oct 26 '12 at 16:21
0

Just remove all spaceholders for the thousands, the dot...

s.replaceAll(".","");
Thomas
  • 650
  • 9
  • 9
0

You should use NumberFormat to parse the values

psabbate
  • 767
  • 1
  • 5
  • 22
0

We can use regular expression to trim out the decimal part. Then use parseLong

Long.parseLong( data.replaceAll("\..*", ""));

jean joseph
  • 82
  • 1
  • 2
-2

If you don't want to loose presision then you should use multiplication

    BigDecimal bigDecimal = new BigDecimal("100.111");
    long l = (long) (bigDecimal.doubleValue() * 1000);<--Multiply by 1000 as it
                                                         is miliseconds
    System.out.println(l);

Output:

100111
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
  • 1
    This is an extremely bad idea. Doubles are not lossless! Following this advice will likely lead to data corruption. – Torque May 16 '14 at 20:35