java.lang.NumberFormatException for converting str

2019-06-28 07:00发布

问题:

I am trying to convert a string to long and it throws the NumberFormatException. I don't think it is beyond range of long at all.

Here is the code to convert, where count_strng is the String I want to convert to long. trim() function is not making any difference.

long sum_link = Long.parseLong(count_strng.trim());

Here is the stacktrace.

java.lang.NumberFormatException: For input string: "0.003846153846153846"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:441)
at java.lang.Long.parseLong(Long.java:483)

Anyone knows what is the exact issue here?

回答1:

Long.parseLong() is trying to parse the input string into a long. In Java, a long is defined such that:

The long data type is a 64-bit two's complement integer.

An integer is defined such that:

An integer (from the Latin integer meaning "whole") is a number that can be written without a fractional component.

The error you are getting shows the input string you are trying to parse is "0.003846153846153846", which clearly does have a fractional component.

You should use Double.parseDouble() if you want to parse a floating point number.



回答2:

As your input string is actually not a long, parsing into long would throw NumberFormatException. Rather try this

Double d = Double.parseDouble(count_strng.trim());
Long l = d.longValue();


回答3:

Long types represents mathematical integers. (Integer also represents mathematical integers, but with a smaller range than Long)

Long and Integer cannot represent values that have a decimal point or a fractional component. The parser enforces this rule by rejecting the string you gave it.

If you want to parse a string that may contain a decimal point and use the resulting value as a Long, you would first have to parse it as a Double and then convert it to a Long.

Conversion from Double to Long can be done one of two ways: Truncating the fractional part (basically just ignoring it) and rounding the fractional part mathematically. To truncate, use a cast, to round use the Math.round() method.

Hers'a an example:

String s = "0.51"; // Greater than 0.50 so will round up
double d = Double.parseDouble(s);

System.out.println(d); // The parsed double

System.out.println((int)d); // Double converted to int and truncated (fractional part dropped)

System.out.println(Math.round(d)); // Double converted to int with mathematical rounding

This code will print

0.51
0
1

Also: trim()is a String function that removes whitespace characters from the string - it does not do any math.