I’m having an issue converting from Fahrenheit to Celsius in Java. I just started learning Java, and am still working my way through books and tutorials.
For my first program, I’m trying to create a basic temperature calculator based on this tutorial.
I’m wanting to extend it’s functionality, and also include a Fahrenheit to Celsius conversion, as well as the base Celsius to Fahrenheit conversion.
So, I got the Celsius to Fahrenheit part working using the example code that was given, and now, using the same code, slightly modified after a lot of trial and error to get it to work, I’m trying to tackle the other half. I got it to work to some degree, but it’s not completely correct.
When I enter, for example, 89 degrees Fahrenheit, it returns 31 Celsius instead of the expected 32. I’m thinking this is an issue in the way the number is getting rounded, but I’m not sure how to go about fixing it. I’ve done some reading, and I think it might be able to be fixed by setting the RoundingMode to “HALF_UP”, but I’m not sure how to do it so that it affects only this conversion, and not the other one that works. This is what I have:
int tempCel = (int) ((int)((Double.parseDouble(tempTextFieldFC.getText()))
- 32) * .55555);
tempCelLabel.setText(tempCel + " ° Celsius");
Any help or suggestions that can be given will be greatly appreciated. Thanks for your time.
Use
Math.round()to perform rounding, instead of casting toint. Casting always rounds towards 0, as per JLS section 5.1.3:Note that
Math.round(double)is still declared to return adouble, as it may be outside the range ofintorlong– but I would expect that not to be a problem in your case.I’d also advise you to split up your code into multiple statements instead: