Converting a string to an integer value

How can I convert a string to an integer?

sorry, not "of new Integer.." but "or new Integer(.."
Message was edited by:

Similar Messages

  • Converting a String to an integer?

    i need to convert a string to an integer..i searched through the site but i didn't find anything...
    Is this conversion possible?

    You didn't look very hard - it's right in the javadocs:
    String s = "44";
    int x = Integer.parseInt(s);I'll leave the exception handling for you.

  • Converting a string to an integer - NumberFormatException

    I have 2 string arrays, one that olds names and one that holds id numbers. They are both stored in a file as Strings. I then read this file into my program and put split the strings up into an array.
    I then try to convert the id to integer inside my program like so:
    public void make_array(String[] car_info) {
                    // put in arraylist and change variable type to correct ones
                    final int ID_INDEX = 0;
                    final int TYPE = 1;
                    int cust_id = 22;
                    String type;
                    //convert to correct variable types
                    try {
                            //convert to string
                            cust_id = Integer.parseInt(car_info[ID_INDEX]);   
                    } catch (NumberFormatException e) { System.out.println(e); }
                    type = car_info[TYPE];
    }I then get the errors when i try this:
    java.lang.NumberFormatException: For input string: "1"
    So the id was stored as "1", but i want to convert it to an integer value. Any ideas on why this happends? Also before i try to convert i output the id from the array and it is correct, after the conversion it is 0, obviously it is not working. But i'm not sure what is wrong.
    Any ideas?

    only works when the string is a single number suchas
    "1" or "4". If you try to use it with the input
    string as a longer one like "123" or "12" itcreates
    a NumberFormatExceptionYou must be mistaken. The value must not be what you
    think it is. Do some debugging:
    String strVal = car_info[ID_INDEX].trim();
    System.out.println("This is the number to be
    parsed -->" + strVal + "<--");
    customer_id = Integer.parseInt(strVal);That is a good idea, but it seems as though the string is fine: I did:
    [email protected]# cat cars
    this output:
    1,5,Renault Clio,Small Car,25,4,false
    As you can see the number 25 is a two figure number, and it looks good. I also output the number in the java program like this:
    System.out.println("the number is ------>" + twodigitnumber + "<------");This output the number: ------->25<---------- So there doesn't seem to be any wierd spacing or characters there.

  • How to convert a string to a currency value ? getting a dump with exception

    I am getting a exception not caught in CX_SY_CONVERSION_NO_NUMBER.
    I am trying to convert a string value with ',' to a currency value.
    I tried using Replace and Condense. But the error still persists.
    Is there a FM or a casting that I can use?

    Sorry I got my question wrong. I have a problem - that when I'm trying to pass a value from a string to a currency field.
    But, the currency field is a field symbol.
    so, I have
    data abc type string.
    abc = "5345"
    <curr_val> = abc.
    now <curr_val> = 0.000
    Please suggest.

  • Converting a string to an integer array

    This is kind of a newbie question, but:
    If I have a string which looks like this: "12,54,253,64"
    what is the most effective/elegant/best/etc. way to convert it into an integer array (of course not including the ","s :-)
    Any suggestions are greatly appreciated.

    Thanks, I'll do that. I was looking at StringTokenizer and other things, but it seems they are not implemented in j2me?

  • Converting a string to the corresponding value of type double

    Hey, im a really noob at this, but I need some help with this question. I've got to complete this in order to progress to my second year although im not doing programming and will not need it in the second year. The question is as follows:
    "Write a method called convertDouble as follows:
    public double convertDouble (String value) {
    This method should convert its parameter (a string like "3.1415") to the corresponding value of type double. If the string supplied is not a valid number, it should return 0.0 as its result. Note that you can use the method Double.parseDouble() to do the hard work for you. "
    To be honest I dont really have a clue what how to write this so any help would be much appreciated. Cheers guys

    Well the simplest way is to use Java's already inbuilt converter:
    which is if you have a string S which represents a double i.e 3.142
    You can use
    double number = Double.parseDouble(S); and thats it.
    The other way to do it is to loop through the string and check whether it is a number
    by using Character.IsDigit(ch) ? or somethign similar.
    and if it is a digit then subtract a fixed amount depending on its ASCII value.
    so if character with a value of 40 represents 0 (im not sure if it does) then
    any Digit character - 40 would give you the decimal value.
    Please ask questions if i dont make sense.
    Edited by: z0rgy on Aug 18, 2008 7:36 AM

  • Coverting from a string to an integer

    Is it possible to covert a string to an integer?
    For example I want to convert the following string values to integers so that I can develop a method to use java.util.Date to test for overlapping appointments.
    markCalendar.addApp(new Appointment("June 1","3pm","4pm", "dentist"));
    I want to convert the startTime and the endTime to integers. And compare the startTime and endTime to a vector of appointments.
    Should this approch work?
    Describes a calendar for a set of appointments.
    @version 1.0
    import java.util.Vector;
    public class CalendarTest
    {  public static void main(String[] args)
          Calendar markCalendar = new Calendar("Mark");
          markCalendar.addApp(new Appointment("June 1","3pm","4pm", "dentist"));
           markCalendar.addApp(new Appointment("June 2","3pm","4pm", "doctor"));
          Appointment toFind = new Appointment("June 2","3pm","4pm", "doctor");
          markCalendar.addApp(new Appointment("June 2","3pm","4pm", "dentist"));
          Appointment dups = (new Appointment("June 2","3pm","4pm", "dentist"));
    Describes a calendar for a set of appointments.
    class Calendar
       Constructs a calendar for the person named.
       public Calendar(String aName)
       {  name = aName;
          appointments = new Vector();
       Adds an appointment to this Calendar.
       @param anApp The appointment to add.
       public void addApp(Appointment anApp)
       Removes an appointment from this Calendar.
       @param anApp The appointment to be removed.
       public void removeApp(Appointment toFind)
          for ( int i = 0; i < appointments.size(); i++)
             if (((Appointment)appointments.get(i)).equals(toFind))
       Tests for duplicate appointment dates.
       public void dupsTest(Appointment app)
          for (int x = 0; x < appointments.size(); x++)
             //Appointment cmp = (Appointment)appointments.elementAt(x);
             //System.out.println("cmp  " + cmp);
             for (int y = appointments.size()-1; y > x; y --)
                Appointment nextApp =(Appointment) appointments.get(y);
                //if (app.equals((Appointment)appointments.elementAt(y)))
                if (app.equals (nextApp))
                {  System.out.println("duplicates  ");
       Prints the Calendar.
       public void print()
       {  System.out.println(name + "               C A L E N D A R");
           System.out.println("Date   Starttime    EndTime   Appointment");
          for (int i = 0; i < appointments.size(); i++)
          {  Appointment nextApp =(Appointment) appointments.get(i);
          //appointments.dupsTest(Appointments anApp);
       private Vector appointments;
       private String name;
       private Appointment theAppointment;
    Describes an appointment.
    class Appointment
       public Appointment(String aDate,String aStarttime,String aEndtime, String aApp)
       {  date = aDate;
          starttime = aStarttime;
           endtime = aEndtime;  
          app = aApp;
    Method to test whether on object equals another.
    @param otherObject  The other object.
    @return true if equal, false if not
    public boolean equals(Object otherObject)
          if (otherObject instanceof Appointment)
          {  Appointment other = (Appointment)otherObject;
             return (date.equals( && starttime.equals(other.starttime)
                     && endtime.equals(other.endtime) && app.equals(;
           else return false;
       Prints the Date, Starttime, Endtime and a description of the
       public void print()  
       {  System.out.println();
          System.out.println(date + "   " + starttime + "          " + endtime
              + "       " + app );
       private String date;
       private String starttime;
       private String endtime;
       private String app;

    First I would like to suggest, DONT use the class names that have already being defined in JAVA, Here you have used, CALENDAR class, this approach should be avoided, If this class is in the same project where you also want to use the JAVA CALENDAR class, then you mite not be able to do so.
    As for the conversion, A simple way is that:
    You already know that the time cannot go more than 2 digits (Specifically not more than 24 hours in case of hours and 60 in case of minutes) and the (am) (pm) takes 2 more places, so what you can do is validate if the string size is 4 or 3, if 4 then take the first 2 substrings i.e. somestring.substring(0,2) and then use the Ineteger.parseInt(some string) method.
    similarly if the String size is 3 then take the first substring
    e.g. somestring.substring(0,1)
    This is how you can convert the string to the Integer and compare it, You can store it as an Integer Object and store it in the Vector If you want to.
    Hope this helps

  • Convert from String to Int

    I have a question.
    How do I convert from String to Integer?
    Here is my code:
    String s="000111010101001101101010";
    int q=Integer.parseInt(s);
    answerStr = String.valueOf(q);
    catch (NumberFormatException e)
    but, everytime when i run the code, i always get the ERROR.
    is the value that i got, cannot be converted to int?
    i've done the same thing in c, and its working fine.

    6kyAngel wrote:
    actually it convert the string value into decimal value.In fact what it does is convert the (binary) string into an integer value. It's the String representation of integer quantities that have a base (two, ten, hex etc): the quantities themselves don't have a base.
    To take an integer quantity (in the form of an int) and convert it to a binary String, use the handy toString() method in the Integer class - like your other conversion, use the one that takes a radix argument.

  • Large integer values


    You could use DecimalData with scale 0.
    Alexis Hassler
    OOsphere France
    (33) 4 37 49 01 28
    -----Message d'origine-----
    De: Kasrul Islam []
    Date: vendredi 3 mars 2000 21:04
    Objet: (forte-users) Large integer values
    Can anyone out there help with a little problem, I have string of numbers
    that I have extracted out of a file, the numbers are all over 10 digits
    when I try to convert this string into a Integer the number gets changed to
    something weird for example.
    Txt : TextData = new(Value = '12345');
    mInt : IntegerData = new(Value = Txt.IntegerValue);
    this works fine but when I try a number like this :
    Txt : TextData = new(Value = '951475978067');
    mInt : IntegerData = new(Value = Txt.IntegerValue);
    then I get the following value in my integerdata object : 2147483647 any
    help will be appreciated, I really need to get the above value as an
    integer because I need to do some calculations with it.
    Thanks in advance.
    Kasrul Islam.
    << Fichier: ATT00000.html>>

  • How do I know if I can convert a String value to an int value or not?

    I want to know how to make the judgment that if I can convert a String value to an int value or not? Assume that I don't know the String is number or letters
    Thank you

    Encephalopathic wrote
    Again, why?One of the problems (have been dued) in my codelab asks us to write a class as follow
    Write a class definition of a class named 'Value' with the following:
    a constructor accepting a single integer paramter
    a constructor with no parameters
    a method 'setVal' that accepts a single parameter,
    a boolean method, 'wasModified' that returns true if setVal was ever called for the object.
    a method 'getVal' that returns an integer value as follows: if setVal has ever been called, it getVal returns the last value passed to setVal. Otherwise if the "single int parameter" constructor was used to create the object, getVal returns the value passed to that constructor. Otherwise getVal returns 0.
    The setVal(int y) returns nothing, so how do I know whether it has been called or not?
    Thank you

  • How to convert string to an integer in SQL Server 2008

    Hi All,
    How to convert string to an integer in sql server,
    Input : string str="1,2,3,5"
    Output would be : 1,2,3,5
    Thanks in advance.

    No, you cannot convert to INT and get 1,2,3 BUT you can get
    Is it ok?
    CREATE FUNCTION [dbo].[SplitString]
             @str VARCHAR(MAX)
        RETURNS @ret TABLE (token VARCHAR(MAX))
        DECLARE @x XML 
        SET @x = '<t>' + REPLACE(@str, ',', '</t><t>') + '</t>'
        INSERT INTO @ret
            SELECT x.i.value('.', 'VARCHAR(MAX)') AS token
            FROM @x.nodes('//t') x(i)
    SELECT * FROM SplitString ('1,2,3')
    Best Regards,Uri Dimant SQL Server MVP,
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Convert an integer value that was created with the Excel DATEVALUE formula to a valid date?

    Hello everyone,
    How can I convert an integer value that was created with the Excel DATEVALUE formula to a valid date in SSIS?
    Is this even possible?
    For example:
    =DATEVALUE("8/22/2008") will format the cell to display 39682.
    Reading the column as a string to get the int value (39682) - how can I turn this into a valid date using SSIS and then importing the real date to sql server?
    Thank you!

    You can use Script component for this and convert your integer values to Date. An example here is following:
    CultureInfo provider = CultureInfo.InvariantCulture;
    string dateString = "08082010";
    string format = "MMddyyyy";
    DateTime result = DateTime.ParseExact(dateString, format, provider);
    Vikash Kumar Singh ||

  • How to convert a String which contains integers to an integer

    Hi, I'm doing a simple user-interaction program. For example I ask how many people are in a group. and they give me an answer with a integer number. But how can I convert the to an real integer value, i.e. How can a String value which contain an integer convert to an integer value?
    InputStreamReader inputStreamR = new                               InputStreamReader(;
    BufferedReader bufR = new BufferedReader(inputStreamR);
    String ans = bufR.readLine();
    and then what? (I want the answer is an integer);

    String ans = bufR.readLine();
    try {
      int ansAsInt = Integer.parseInt(ans);
    } catch (NumberFormatException nfe) {
      // What happens if the String was not an integer

  • Need help to convert this format of string in a int value?

    public static int isNumber( String number, int defaultValue ) {
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Hi, I have the above method that converts a string Number into a int value. It works fine if the string is a normal number 234 (without spaces) but I have a string in the following format:
    That is I have a "space" then a "Pound" sign then two numbers then a comma followed by three numbers and then a space again.
    Is there any way I can convert this format into a simple int value?
    Thanks for any guidance.

    Hi, I tried the following code but it don't seem to work
         public static int isNumberTrimSpaces( String number, int defaultValue ) {
              String parsed = "";
              for (int i = 0 ; i < number.length() && number.charAt(i) != ',' ; i++)
             if (Character.isDigit(number.charAt(i))) {
             parsed += number.charAt(i);}
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Any Ideas? Also will the loop get rid of the pound sign?

  • "Property value is not valid" when PropertyGridView tries to convert a string to a custom object type.

    I have a problem with an PropertyGrid enum property that uses a type converter.
    In general it works, but when I double clicking or using the scoll wheel,  an error message appears:
    "Property value is not valid"
    Details: "Object of type 'System.String' cannot be converted to type 'myCompany.myProject.CC_myCustomProperty."
    I noticed that the CommitValue method (in PropertyGridView.cs) tries to convert a string value to a CC_myCustomProperty object.
    Here is the code that causes the error (see line 33):
    (Using the .net symbols from the PropertyGridView.cs file)
            internal bool CommitValue(GridEntry ipeCur, object value) {   
                Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose,  "PropertyGridView:CommitValue(" + (value==null ? "null" :value.ToString()) + ")");   
                int propCount = ipeCur.ChildCount;  
                bool capture = Edit.HookMouseDown;  
                object originalValue = null;   
                try {   
                    originalValue = ipeCur.PropertyValue;   
                catch {   
                    // if the getter is failing, we still want to let  
                    // the set happen.  
                try {  
                    try {   
                        SetFlag(FlagInPropertySet, true);   
                        //if this propentry is enumerable, then once a value is selected from the editor,   
                        //we'll want to close the drop down (like true/false).  Otherwise, if we're  
                        //working with Anchor for ex., then we should be able to select different values  
                        //from the editor, without having it close every time.  
                        if (ipeCur != null &&   
                            ipeCur.Enumerable) {  
                        try {   
                            Edit.DisableMouseHook = true;  
    /*** This Step fails because the commit method is trying to convert a string to myCustom objet ***/ 
                            ipeCur.PropertyValue = value;   
                        finally {   
                            Edit.DisableMouseHook = false;  
                            Edit.HookMouseDown = capture;   
                    catch (Exception ex) {   
                        ShowInvalidMessage(ipeCur.PropertyLabel, value, ex);  
                        return false;  
    I'm stuck.
    I was wondering is there a way to work around this? Maybe extend the string converter class to accept this?
    Thanks in advance,

    Thank you for your post!  I would suggest posting your question in one of the MS Forums,
     MSDN Forums » Windows Forms » Windows Forms General
     located here:
    Have a great day!

Maybe you are looking for

  • Not getting all of my email

    Somehow, I'm not getting all of my email (via iCloud).  My wife forwared an email to me, I got the "ding" but no email.  She sent it to another IMAP account that I have and I got it just fine.  She repeatedly tried to send it to my .mac account and n

  • AP: 3.4.1, On import. Can't select expanded previews

    Finally upgraded to AP 3.4.1.OSX 10.7.5. New in this version only, when importing (uploading) RAW Canon files (via FW 800 reader), I can no longer select (or deselect) a file if the preview image has been enlarged, i.e. double clicked on.  In every v

  • Sequencing Java

    Hi all I googled how to sequence java using app-v 5 however its a rather confusing as one article will talk about how to use the deployment. properties file another will talk about using power shell to use only the current version of java in the bubb

  • How to download a specific previous version (10.3.1)?

    One of our customers has been asked by the office of state revenue to run a specific version of Adobe reader for viewing documents on their site (10.3.1) but do not provide it. 10.4.1 (the latest at time of writing) does not work with their site. Is

  • SMTP send mail message

    SMTP send mail message is giving 'unkown mime version' error(error code 16500). The same mail server works when sending by Netscape mail.Any help greatly appreciated.