Two Laptop Bag*
The moose likes Java in General and the fly likes Converting a String to the appropriate numeric data type... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Converting a String to the appropriate numeric data type..." Watch "Converting a String to the appropriate numeric data type..." New topic
Author

Converting a String to the appropriate numeric data type...

Landon Blake
Ranch Hand

Joined: Dec 04, 2003
Posts: 121
Is there a Java class that provides a method to convert a string to the appropriate numeric data type (int, float, double) based on the contents of the string. (Whether the String contains a decimal point and the number of digits.)

I can write this logic from scratch, but want to use the "standard" way to do this, if there is one.

Thanks,

Landon
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
You could use either java.text.NumberFormat or java.text.DecimalFormat above all if the String contains special symbols like: thounsand separators, currency symbols or percentage symbols.

If you know that datatype of the String before procesing it and if the String does not contain special characters like those mentioned above, you could use either:

  • java.lang.Byte.paseByte(String)
  • java.lang.Integer.parseInt(String)
  • java.lang.Long.parseLong(String)
  • java.lang.Float.parseFloat(String)
  • java.lang.Double.parseDouble(String)



  • Another option could be: Double.valueOf(String).doubleValue()
    [ December 19, 2006: Message edited by: Edwin Dalorzo ]
    Jim Yingst
    Wanderer
    Sheriff

    Joined: Jan 30, 2000
    Posts: 18671
    If you're using JDK 5+ I would recommend Scanner, using methods like hasNextInt() and nextInt(). The nice thing about Scanner is that if the input can't be pared as an int (or whatever numeric type you want) you can detect this easily beforehand using hasNextInt(). Prior to JDK 5 the standard option was to use Integer.parseInt(), but in that case you need to catch an exception in case of bad input.

    And yes, I agree that NumberFormat / DecimalFormat are probably best if you need to customize the format options. In my experience that's been pretty rare, but it could happen.


    "I'm not back." - Bill Harding, Twister
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Converting a String to the appropriate numeric data type...
     
    Similar Threads
    JPA Query using " where in" and setParameter
    Read everything as a String?
    convert timestamp to double
    Number Stored as Text in Excel Output
    Validation for numeric input in applications