Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String to a Double (A better way?)

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
double customsValue = Double.parseDouble(customsValueText) / 100.0;
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic