Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Formatting math formulas

Emily Burgardt
Greenhorn
Posts: 1
Very new to Java, and I know this is a very simple question, but:

I was working on a program that converts Fahrenheit to Celsius and was struggling to figure out why my output was always "0". Eventually I figured out it was a formatting issue.

I ended up having to change my formula from this:
celsius = ((5 / 9) * (fahrenheit - 32));

To this:
celsius = ((fahrenheit - 32) * 5) / 9;

It fixed my problem, but I'd still like to know for future reference - is there any particular reason why the first one wasn't working for me? Am I missing something obvious here?

Carey Brown
Bartender
Posts: 2980
46
• 1
Your culprit is 5/9. This is done in integer arithmetic and yields zero.

Try
celsius = ((5.0 / 9.0) * (fahrenheit - 32));

If celsius is defined as an int then you'll have to cast the result to an int before assigning it to celsius.

Campbell Ritchie
Marshal
Posts: 55678
161
Welcome to the Ranch

To expand what CB said: integer division follows a convention which goes back sixty years: the quotient is rounded towards 0. If you divide 999999999 by 1000000000 you don't get it rounded up to 1, but rounded towards 0:-