I’m writing a program that does many things, but one of them is converting Celcius to Fahrenheit. After I did this, I decided to allow the reverse, so that’s what I’ve done. I get correct answers when I convert Celcius to Fahrenheit, but for some reason I’m getting slightly off answers when converting Fahrenheit to Celcius. Here’s my code:
String celcius = jTextArea3.getText();
String fahren = jTextArea7.getText();
if (fahren.equals("")) {
double tempFahr;
double Input = Double.parseDouble(jTextArea3.getText());
tempFahr = Input * 9 / 5 + 32;
jTextArea7.setText(tempFahr + "");
}
else
{
double tempCelc;
double Input = Double.parseDouble(jTextArea7.getText());
tempCelc = (Input -32) * 5 / 9;
jTextArea3.setText(tempCelc + "");
}
It’s simple code, but I’m wondering if it could be something very small that I’m not seeing. It could be my formula I suppose, but I’m pretty sure it’s not, I’ve looked into it. Can anyone help?
An example of the off answers I get is:
1 Celcius = 33.8 Fahrenheit
33.8 Fahrenheit = 0.9999999999999984 Celcius
@Greg is right
You just need to do some rounding:
Anyway – don’t worry your values are just fine, but to compare (or print, which is current use case) them
you need some epsilon/precision, because – again: floating point calculations are almost never “exact”.