Reputation: 239
Does the method setText() always set to a string? If we want to set a Double value to the text field, hows it done?
Upvotes: 2
Views: 23594
Reputation: 23037
setText()
only accepts a String
. In order to insert a double
, you can just concatenate the double to a string:
double someDouble = 2.5;
yourJTextField.setText("" + someDouble);
Notice that the double displays as 2.5
. To format the double, see String.format()
.
Edit, 5 years later
I agree with the other answers that it is cleaner to use Double.toString(someDouble)
to do the conversion.
Upvotes: 1
Reputation: 692071
You transform the Double to a string first:
textField.setText(myDouble.toString());
At the risk of contradicting the other answers here, a primitive double should, IMHO, be transformed to a String using Double.toString(d)
or String.valueOf(d)
, which expresses the intent more clearly (and is more efficient) than concatenation.
Upvotes: 4
Reputation: 324157
If you have an actual Double object then you can use:
textField.setText( doubleValue.toString() );
Or, if you have a double primitive you can use:
textField.setText( doubleValue + "" );
Upvotes: 2