Search code examples
javastringlong-integerformatexception

Getting number format excpetion


Unable parsing below number.

Long.parseLong("1000.00".length() > 0 ? "1000.00" : "0")

While parsing "1000.00" then getting number format exception.

How to parse "1000.00" this string into long in java?


Solution

  • longs are integral numbers. "1000" would work. "1000.00" has a fractional portion (which is zero, but still), which will not.

    How to parse "1000.00" this string into long in java?

    In the general case, you can't; a long can't store a fractional portion.

    Now, in your specific example, the fractional portion is zero, so you could just remove it:

    long result = Long.parseLong("1000.00".split("\\.")[0]);
    

    Or you could parse it as a double and then truncate it:

    long result = (long)Double.parseDouble("1000.00");
    

    ...but again, just beware that long is an integral type that doesn't support fractional values.