Convert String (representing decimal number) to long

11,573

Solution 1

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();

Solution 2

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();

Solution 3

'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.

Share:
11,573
temelm
Author by

temelm

Updated on June 13, 2022

Comments

  • temelm
    temelm almost 2 years

    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.

  • Uncle Iroh
    Uncle Iroh over 11 years
  • Kenogu Labz
    Kenogu Labz over 11 years
    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.
  • Torque
    Torque almost 10 years
    This is an extremely bad idea. Doubles are not lossless! Following this advice will likely lead to data corruption.
  • Smith
    Smith almost 10 years
    this would result in wrong number, 100.00 would be 10000