• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String to a Double (A better way?)

 
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
double customsValue = Double.parseDouble(customsValueText) / 100.0;
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Heroic work plunger man. Please allow me to introduce you to this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic