Calculator - setText (String) doesn't work with Doubles
So I am trying to make a calculator and I am using JFrame code and trying to use inline math to find the square root of a number. Below is the code where the problems occur. "Display.setText (Math.sqrt (Double.parseDouble (display.getText ())));"
gives me the error "Method setText (String) in type JTextComponent is not applicable for arguments (double)"
sqrt = new JButton("SQRT");
sqrt.setBounds(298, 141, 65, 65);
sqrt.setBackground(Color.BLACK);
sqrt.setForeground(Color.BLACK);
sqrt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setTempFirst(Double.parseDouble(display.getText()));
display.setText(Math.sqrt(Double.parseDouble(display.getText())));
operation[5] = true;
}
});
add(sqrt);
source to share
As you said, this method expects a String instead of a double, so you must convert the result
Math.sqrt(Double.parseDouble(display.getText()))
to double, for example:
String.valueOf(Math.sqrt(Double.parseDouble(display.getText())))
or
Math.sqrt(Double.parseDouble(display.getText()))+""
The best way would be to format this result to some decimal places, for example:
String.format( "%.2f", YOUR_NUMBER )
...
source to share