-2

I have to convert string welcome into number format. But when I'm going to execute it throws exception

Exception in thread "main" java.text.ParseException: Unparseable number: "Welcome"
    at java.text.NumberFormat.parse(Unknown Source)
    at sample.Sam.main(Sam.java:13)

package sample;

import java.text.DecimalFormat;
import java.text.ParseException;

public class Sam {

    public static void main(String[] args) throws ParseException {
        // TODO Auto-generated method stub
            String str="Welcome,@123";
            DecimalFormat df = new DecimalFormat(str);

            System.out.println( df.parse(str));

    }

}
Cœur
  • 37,241
  • 25
  • 195
  • 267

3 Answers3

1

The code you shared does no throw the Exception you copied...

Anyway, here is a code that will extract an integer from any string:

        String str="Welcome,@123";
        Pattern p = Pattern.compile( "\\D*(\\d+)\\D*" );
        Matcher m = p.matcher(str);
        if ( m.matches() )
        {
            int value = Integer.parseInt( m.group(1) );
            System.out.println( value );
        }
        else
        {
            System.out.println("no number found");
        }
StephaneM
  • 4,779
  • 1
  • 16
  • 33
1

You need to declare the format first with one string that is a valid DecimalFormat pattern and then you can parse the real string:

String pattern = "'Welcome,@'0"; //0 is a placeholder, see the link for the others
DecimalFormat df = new DecimalFormat(pattern);

String input = "Welcome,@123";
System.out.println(df.parse(input)); //prints 123

As , is also a placeholder, I have had to quote the text 'Welcome,@'.

weston
  • 54,145
  • 21
  • 145
  • 203
0

Everything is possible, but .. In that case you have to find just a numbers from that string look look at this

String s = "...stuff...";

    for (int i = 0; i < s.length(); i++){
        char c = s.charAt(i);        
        //Process char
    }

For recognize if the char is number should be possible to use that

Character.isDigit(string.charAt(0))

So something like:

String s = "..ag123";
String numStr = "";
    for (int i = 0; i < s.length(); i++){
        char c = s.charAt(i);        
        if(Character.isDigit(s.charAt(i))){
              numStr += s.charAt(i);
         }
    }
 Integer.parseInt(numStr); 

For demimal you have to also recognize decimal (maybe also thousands?) separator :) But something in this way..

Btw you can still probably use decimal formatter but you need to set pattern for that (not sure if its possible like string pattern) - you cant find it in doc, Im not sure, but it will be something like [^0123456789][123456789][separators][0123456789][^0123456789] (missing nonmandatory and repeating there)

Community
  • 1
  • 1
xxxvodnikxxx
  • 1,270
  • 2
  • 18
  • 37