Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Dividing Ints  RSS feed

 
Aaron Parker
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to divide ints with a result float. It's displaying one decimal place and rounding down.
public static float calcGPA(int credHrs, int numPoints) {
float GPA = numPoints / credHrs;
return GPA;
}
What am I doing wrong? I'm wanting a result of 2 or 3 decimal places.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch, Aaron!
Your division calculation involves only int values. So, as int division is performed, the result is truncated to an int result with the decimal part being essentially chopped off entirely. This int result is then promoted to a float during the assignment. So, the value assigned to the float was an int. Note that when whole numbers are converted to floats and displayed, they often include a single .0 after the whole number, so to speak.
You likely want to convert the operands of the division to floats before the division operator is applied and the result assigned to your float variable. This is pretty easy. Just promote one of your int operands to a float and they will both be automagically promoted to a float, and floating point division will ensue.
In other words, change float GPA = numPoints / credHrs; to float GPA = (float)numPoints / credHrs;
Then, if you're concerned about the format of any displayed output, you could investigate using java.text.DecimalFormat.
Good luck, and let us know how you make out.
[ January 31, 2004: Message edited by: Dirk Schreckmann ]
 
Maarten Vergouwen
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First do a typecast of the result of your division to the appropriate form, a Float in this case:

After that you can round it to whatever precision you want.
 
Aaron Parker
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That worked wonderfully. Thank you. How do I round the result to a particular number of decimal places?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you trying to do this for display purposes only?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!