Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String to Long conversion, truely beginner question

 
zhen su
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple as below, why "1.0" can not be converted into Long?

THanks,

-----------------------------

public class Test {


public static void main(String[] args) {


String value = "1.0";

Long longValue = new Long(0);
if (value != null && value.trim().length() > 0) {
try {
longValue = new Long(value);
}
catch(NumberFormatException ex) {
System.out.println ("Cannot convert to long - ignoring: ");
ex.printStackTrace();
}
}
}
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See Sun's API for Long...

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Long.html

You'll note that the constructor Long(String) throws a NumberFormatException "if the String does not contain a parsable long." And in order to be a parsable long, "the characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ... to indicate a negative value."

Therefore, "1.0" is not a parsable long. If your String was simply "1" (without a decimal point), then it would work.
[ September 14, 2004: Message edited by: marc weber ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To put it another way, long is an integral data type. 1.0 is not an integer.

In Java, the literal numeric value 1.0 is a double, which is a floating point data type. Note that you could parse the String "1.0" into a double.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic