• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: [OT]Re: rounding to a multiple of x?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [OT]Re: rounding to a multiple of x?


  • Subject: Re: [OT]Re: rounding to a multiple of x?
  • From: Daniel Todd Currie <email@hidden>
  • Date: Wed, 19 May 2004 13:06:37 -0700

I think we're trying a bit too hard here... The following will work for any value (float or int) of x:

int newX = ceil( (double)x / 4 ) * 4

You'll need to include math.h


On 2004 May 19, at 11:58, Edward K. Chew wrote:

On May 19, 2004, at 13:07, Graham J Lee wrote:

On 2004-05-19 16:47:23 +0100 email@hidden wrote:

Greetings,
I can't seem to figure out how to roundup to a multiple of a number ie if i have 1149 and i want to round up to a multiple of 4 how would accomplish this? any direction would be great

If we're talking integers, and we call 1149 'x' and 4 'y'...

y*(x/y+1)

But if x and y were both 4, you'd be unnecessarily rounding up to 8, right? How about this:

((x + y - 1) / y) * y

I think it'll work as long as x >= 0. For negative numbers, the y - 1 would have to go, so the general case for integers might look like this:

((x < 0 ? x : x + y - 1) / y) * y

Hmm...I don't particularly like that conditional logic in there, though. Maybe there's a better way. If you knew that y was always a power of 2, you could use some bit logic like so:

(x + y - 1) & -y

That should even work for negative x values, I think.

-Ted
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.


References: 
 >[OT]Re: rounding to a multiple of x? (From: Graham J Lee <email@hidden>)
 >Re: [OT]Re: rounding to a multiple of x? (From: "Edward K. Chew" <email@hidden>)

  • Prev by Date: Re: Lifetime of an NSURLHandle
  • Next by Date: Re: [firstPath appendBezierPath: [secondPath bezierPathByReversingPath]];
  • Previous by thread: Re: [OT]Re: rounding to a multiple of x?
  • Next by thread: Re: rounding to a multiple of x?
  • Index(es):
    • Date
    • Thread