user1216129
user1216129

Reputation: 41

converting String into long in java

I couldn't convert a String s="45,333" into number like long or double. Can anyone help me to solve the issue.. i have added the model snippet, when i try to run that code it showing NumberFormatException..

public static void main(String args[])
{
long a=85200;
NumberFormat numberFormat=NumberFormat.getNumberInstance();
String s=numberFormat.format(a);
Long l=Long.parseLong(s.toString());
System.out.println("The value:"+s);
System.out.println("The value of long:"+l);
}

Upvotes: 1

Views: 6731

Answers (4)

hari
hari

Reputation: 1963

long l = Long.valueOf(s);
System.out.println("The value of long:"+l);

Upvotes: -1

user784540
user784540

Reputation:

Consider NumberFormat.parse() method instead of Long.parseLong().

Long.parseLong() expects String without any formatting symbols inside.

Upvotes: 14

fivedigit
fivedigit

Reputation: 18702

As pointed out you can use NumberFormat.parse() like this:

public static void main(String args[]) {
    long a=85200;
    NumberFormat numberFormat=NumberFormat.getNumberInstance();
    String s=numberFormat.format(a);
    Long l;
    try {
        l = numberFormat.parse(s.toString()).longValue();
    } catch (ParseException ex) {
        l = 0L;
        // Handle exception
    }
    System.out.println("The value:"+s);
    System.out.println("The value of long:"+l);
}

Upvotes: 2

biziclop
biziclop

Reputation: 49814

Mixing NumberFormat and Long.parseLong() isn't a good idea.

NumberFormat can be locale-aware (in your example it uses the default locale for your computer) or you can explicitly specify format patterns, whereas the parseXXX() methods of Number subclasses only read "plain" numbers (optional minus sign+digits).

If you formatted it with NumberFormat, you should use NumberFormat.parse() to parse it back. However you shouldn't depend on the default locale, try to specify one instead (or use DecimalFormat with a pattern). Otherwise you're likely to encounter some nasty and hard to detect bugs.

If you don't care about the format, consider using Long.toString() to convert a long value into string and Long.parseLong() to convert it back. It's easier to use, thread safe (unlike NumberFormat) and works the same everywhere.

Upvotes: 3

Related Questions