convert string to integer or float


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: convert string to integer or float

  1. #1
    Join Date
    Mar 2003
    Posts
    2

    convert string to integer or float

    Is there any sipmle way to determin if a string like "123" or "2.4", contains integer values or floats.
    zolf

  2. #2
    Join Date
    Mar 2003
    Posts
    7

    123 can be float

    123 can be treated safely like float. It depends on the validation rules. I doubt you will make an end user write 123.0

    In Java they have made the same assumption. Check the code:

    public static void stringToFloat() {
    String strInt = "123";
    String strFloat = "2.4";
    try {
    int intVal1 = Integer.parseInt(strInt);
    System.out.println("Int to Int: " + intVal1);

    float flVal1 = Float.parseFloat(strInt);
    System.out.println("Int to Float: " + flVal1);

    float flVal2 = Float.parseFloat(strFloat);
    System.out.println("Float to Float: " + flVal2);

    // throws exception
    int intVal2 = Integer.parseInt(strFloat);
    System.out.println("Float to Int: " + intVal2);

    }
    catch ( NumberFormatException nfe ) {
    nfe.printStackTrace();
    }
    }

    the output is:

    Int to Int: 123
    Int to Float: 123.0
    Float to Float: 2.4
    java.lang.NumberFormatException: 2.4
    at java.lang.Integer.parseInt(Integer.java:435)
    at java.lang.Integer.parseInt(Integer.java:476)
    at com.ossoba.test.FloatNIntParse.stringToFloat(FloatNIntParse.java:30)
    at com.ossoba.test.FloatNIntParse.main(FloatNIntParse.java:11)


    If you want to specifically differentiate int form float you can use something like:

    public static boolean isFloat(String value) {
    return value.indexOf('.') != -1;
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center