Convert String (representing decimal number) to long
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.
temelm
Updated on June 13, 2022Comments
-
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 over 11 years
-
Kenogu Labz over 11 yearsYeah, 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 almost 10 yearsThis is an extremely bad idea. Doubles are not lossless! Following this advice will likely lead to data corruption.
-
Smith almost 10 yearsthis would result in wrong number, 100.00 would be 10000