Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2012
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    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?

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    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.

  • Users who have thanked Fou-Lu for this post:

    Atlan (08-24-2012)

  • #3
    New Coder
    Join Date
    Jul 2012
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Complete success! Thanks a bunch.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •