File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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

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.


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

    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:
    subject: Converting a String to the appropriate numeric data type...
    It's not a secret anymore!