0

My String result is: 3.1

I want to convert it into long :

I use some code like :

String txt_capplot="3.1";
Long.parseLong(String.valueOf(txt_capplot));

After Execute It made some error like:

java.lang.NumberFormatException: For input string: "3.1"

How to solve this?

3 Answers 3

2

Long is like integer it cant have decimal on them, but it will round it off.

solution:

you need to parse it to double first and then cast it to long.

sample:

    String s = "3.1";
    double d = Double.valueOf(s);
    long l = (long) d;
Sign up to request clarification or add additional context in comments.

Comments

0

Since long does not contains decimal fractions, So need to convert your String to double and then the long.

You should try this one line solution :

Double.valueOf(txt_capplot).longValue();

Comments

0

Long doesn't have a decimal part so you need to decide if you want to round it or truncate it. This code shows both

package se.wederbrand.stackoverflow;

public class ConvertToLong {

    public static void main(String[] args) {
        String s = "3.6";
        double d = Double.parseDouble(s);
        long truncated = (long) d;
        long rounded = Math.round(d);

        System.out.println(" original: " + s);
        System.out.println("truncated: " + truncated);
        System.out.println("  rounded: " + rounded);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.