• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting double to string

 
Annie Hampton
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a double that I want to display on a UI component that is expecting a String. As in,
txtBox.setText("I want my double value displayed here");
Why can't I cast it? What do I need to do?
TIA!
 
Junilu Lacar
Bartender
Posts: 7480
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use String.valueOf()
Junilu
 
Greg Brouelette
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An even faster trick is to do this:

If you simply concat an empty string with a double (or int or float) it will automatically make it into a String.
 
Junilu Lacar
Bartender
Posts: 7480
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

double d = 0.02;
String temp = "" + d;
System.out.println(" the number is " + temp );

If you do this, you don't really need to use a temp variable. The "" + something form seems a little kludgy but that's probably just me.
Junilu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic