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

String to Long conversion, truely beginner question

zhen su

Joined: Sep 14, 2004
Posts: 1
Simple as below, why "1.0" can not be converted into Long?



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: ");
marc weber

Joined: Aug 31, 2004
Posts: 11343

See Sun's API for Long...

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
Dirk Schreckmann

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]
Consider Paul's rocket mass heater.
subject: String to Long conversion, truely beginner question
It's not a secret anymore!