aspose file tools*
The moose likes Beginning Java and the fly likes String to Long conversion, truely beginner question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String to Long conversion, truely beginner question" Watch "String to Long conversion, truely beginner question" New topic
Author

String to Long conversion, truely beginner question

zhen su
Greenhorn

Joined: Sep 14, 2004
Posts: 1
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

Joined: Aug 31, 2004
Posts: 11343

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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
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.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String to Long conversion, truely beginner question