File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes String to a Double (A better way?) 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 a Double (A better way?)" Watch "String to a Double (A better way?)" New topic
Author

String to a Double (A better way?)

Anthony Smith
Ranch Hand

Joined: Sep 10, 2001
Posts: 285
Double customsValue =
new Double( customsValueText.
substring(0,customsValueText.length() -2).concat("." +
customsValueText.
substring(customsValueText.length() - 2)));

All I was doing is taking a value that I receive in the form of a String and making it a Double. BUT, the last two digits in the string represent the decimal places.

Is there a better way to do it than I did?
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
double customsValue = Double.parseDouble(customsValueText) / 100.0;
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
You may want to consider converting this value to an int or long instead. This depends a lot on what you are doing with this value afterwards. You should realize that floating-point variables (ones with type float or double) are rarely ever exact representations. This especially becomes a problem if you need to compare equality between to numbers. If you need more information about the limitations of float and double, you should google for the specifics about how Java represents them in memory.

Layne


Java API Documentation
The Java Tutorial
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: String to a Double (A better way?)