Does setText() method always set value to a string?

19,417

Solution 1

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.

Solution 2

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.

Solution 3

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 + "" );
Share:
19,417
Toms
Author by

Toms

NEW IN PROGRAMMING

Updated on July 26, 2022

Comments

  • Toms
    Toms almost 2 years

    Does the method setText() always set to a string? If we want to set a Double value to the text field, hows it done?