Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Landon Blake
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Posts: 18671
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic