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

Rounding up?  RSS feed

 
Sam Bluesman
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Say I have the variable double Number and it has the value 8.8. How do i round this number up to 9 and then store it as an integer?
[ February 10, 2006: Message edited by: Sam Bluesman ]
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look in class java.lang.Math
 
Sam Bluesman
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well the problem I have is this you see:

I want to divide two numbers as such:



Ive tested that the number of students and the room capacity values are correct through the println statements. However, I get the following output:

99
50
here: 1.0
78
50
here: 1.0
101
50
here: 2.0
201
50
here: 4.0
151
50
here: 3.0

I dont understand how, for example, given the code ive written, 151 / 50 = 3.0 . Surely it should have a decimal places after it as a fraction??? whats going on? The same happens when i try Math.ceil.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
151 / 50 does NOT equal 3.0.

since both 151 and 50 are ints, you are doing integer division. the value returned is the integer "3". when you store that in your double, the "3" gets promoted to a double, becoming "3.0"

you can correct this by casting one of your values to a double first:

sessionsRequired = (double)numberOfStudents / roomCapacity;
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You've fallen prey to "integer division". When you divide one integer expression by another the result is an integer, rounded closer to 0 if necessary:

3/2 == 1
-3/2 == -1

To get a floating point result, make the numerator or divisor a floating point expression, for example:

int x = ...
int y = ...
double q = x/(double)y;
[ February 10, 2006: Message edited by: Jeff Albertson ]
 
Sam Bluesman
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. Will try and not make that mistake again!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!