Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-24-2012, 04:17 AM   PM User | #1
Atlan
New Coder

 
Join Date: Jul 2012
Posts: 14
Thanks: 2
Thanked 0 Times in 0 Posts
Atlan is an unknown quantity at this point
Rounding up an integar

Hi all

I'm trying to write a small function which has to, at one point, round a number UP to the nearest multiple of 5.

In theory, the results should be:
4 rounds up to 5
5 rounds up to 5
6 rounds up to 10
7 rounds up to 10
8 rounds up to 10
9 rounds up to 10
10 rounds up to 10

After a fair bit of experimentation, I ended up with the following, but it doesn't work properly.
Code:
for(int i = 0; i < 40; i++)
		{
			int temp = (int) (Math.ceil(i/5)*5); 
			System.out.println("I = " + i + ", rounded = " + temp);
		}
This code rounds DOWN, so 9 rounds down to 5. Anyone know how to make it round UP?
Atlan is offline   Reply With Quote
Old 08-24-2012, 05:18 AM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,635
Thanks: 4
Thanked 2,448 Times in 2,417 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
You're ceil call is going against an integer value. 6 / 5 is 1, multiplied by 5 is 5. You need to convert that to a double, so 6 / 5.0 is 1.2 rounded up is 2 * 5.
So simply divide by 5.0 to force an implicit cast to a double.
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
Atlan (08-24-2012)
Old 08-24-2012, 05:55 AM   PM User | #3
Atlan
New Coder

 
Join Date: Jul 2012
Posts: 14
Thanks: 2
Thanked 0 Times in 0 Posts
Atlan is an unknown quantity at this point
Complete success! Thanks a bunch.
Atlan is offline   Reply With Quote
Reply

Bookmarks

Tags
java, math, round, round up, rounding

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:05 PM.


Advertisement
Log in to turn off these ads.