#### Archived

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

# Ceil

This topic is 5343 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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
#include <cmath>

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

##### Share on other sites
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
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
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
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
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?!?!?

1. 1
Rutin
27
2. 2
3. 3
4. 4
5. 5

• 11
• 9
• 9
• 9
• 14
• ### Forum Statistics

• Total Topics
633313
• Total Posts
3011316
• ### Who's Online (See full list)

There are no registered users currently online

×