I have a GUI which works like the following: there are 2 buttons and 1 textField. The textField is used to hold double/float values, 1 of the buttons adds a value (in this case, 0.1) and the other one subtracts (adds -0.1).
Here is my following problem: after pressing one of the buttons many times, the resulting value is not behaving the way I would like. In other words, instead of "1.5" turning into "1.6", it will be something like "1.5999998". I have tried many changes (like changing the variables types and the value to add/subtract), but none of these worked. Here's a piece of my code:
public void sumTextField(){
try{
if(textField.getText() == "")
textField.setText("0.1");
else{
float aux = Float.parseFloat(textField.getText());
aux += 0.10000000;
textField.setText(String.valueOf(aux));
}
}
catch(NumberFormatException nfe){
nfe.printStackTrace();
JOptionPane.showMessageDialog(null, "Please, provide a valid value in the text field!", "Impossible sum", JOptionPane.INFORMATION_MESSAGE);
}
}
public void subtractTextField(){
try{
if(textField.getText() == "")
textField.setText("-0.1");
else{
float aux = Float.parseFloat(textField.getText());
aux -= 0.10000000;
textField.setText(String.valueOf(aux));
}
}
catch(NumberFormatException nfe){
nfe.printStackTrace();
JOptionPane.showMessageDialog(null, "Please, provide a valid value in the text field!", "Impossible subtraction", JOptionPane.INFORMATION_MESSAGE);
}
}
Any ideas are welcome