• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# Ceil

## Recommended Posts

kelaklub    160
Microsoft excel has a CEILING method that will ceil a number to a certain precision. Does anyone know if something similar is available for C++. Thanks.

##### Share on other sites
marijnh    182
#include <cmath>

double c1 = std::ceil(2.5);
float c2 = std::ceilf(2.5f);

##### Share on other sites
kelaklub    160
I was thinking more along the line if you had a number like 7.1, and you needed to take the CEIL to the nearest one sixteenth of an inch(0.0625). Excel lets you do CEILING(7.1, 0.0625) and gives back 7.125. Is there a c++ way to do this?

##### Share on other sites
Brother Bob    10344
This will round v to nearest multiple of q.
v = 7.1;q = 1/16;r = q*round(v/q);

round() is a function that rounds to nearest integer (code taken from a MALTAB script of mine). Replace round with ceil/floor to round up/down to nearest multiple.

##### Share on other sites
kelaklub    160
That is so awesome. I was doing something stupid like iterating through a for loop, to acheive the same result. But what you suggested is just so much more cleaner, probably alot more efficient to. Thanks much.

##### Share on other sites
Zahlman    1682
If it''s that valuable to you, you should probably encapsulate it in a function:

double granularCeil(double input, double quantum) {
return std::ceil(input/quantum) * quantum;
}

Handling a quantum of 0 gracefully, dealing with floats (and possibly other numeric types? Do you maybe have a Rational number class you''d want to do this with?) etc. is left as an exercise for the reader.

##### Share on other sites
rypyr    252
quote:
Original post by kelaklub
I was ... iterating through a for loop ... But what you suggested is just so much more cleaner, probably alot more efficient to..

Probably?!?!?