programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Rounding up?

Ranch Hand
Posts: 191
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 ]

Ranch Hand
Posts: 1780
Take a look in class java.lang.Math

Sam Bluesman
Ranch Hand
Posts: 191
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.

lowercase baba
Bartender
Posts: 12601
50
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
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
Thanks guys. Will try and not make that mistake again!

 It's a pleasure to see superheros taking such an interest in science. And this tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS