Rounding Up and Down a Number C++

Rounding up and down a number C++

std::ceil 

rounds up to the nearest integer

std::floor 

rounds down to the nearest integer

std::round 

performs the behavior you expect

please give a use case with numbers if this does not provide you with what you need!

Rounding integer division (instead of truncating)

int a = 59.0f / 4.0f + 0.5f;

This only works when assigning to an int as it discards anything after the '.'

Edit:
This solution will only work in the simplest of cases. A more robust solution would be:

unsigned int round_closest(unsigned int dividend, unsigned int divisor)
{
return (dividend + (divisor / 2)) / divisor;
}

How to round up or down in C#?

Try using decimal.Round():

decimal.Round(x, 2)

Where x is your value and 2 is the number of decimals you wish to keep.

You can also specify whether .5 rounds up or down by passing third parameter:

decimal.Round(x, 2, MidpointRounding.AwayFromZero);

EDIT:

In light of the new requirement (i.e. that numbers are sometimes rounded down despite being greater than "halfway" to the next interval), you can try:

var pow = Math.Pow(10, numDigits);
var truncated = Math.Truncate(x*pow) / pow;

Truncate() lops off the non-integer portion of the decimal. Note that numDigits above should be how many digits you want to KEEP, not the total number of decimals, etc.

Finally, if you want to force a round up (truncation really is a forced round-down), you would just add 1 to the result of the Truncate() call before dividing again.

How to round a number in C?

You need to import <math.h> header :

#include <math.h> //don't forget to import this !

double a;
a = round(5.05286); //will be rounded to 5.00

This function has analog definitions for every type, which means that you can pass the following types and it'll be rounded to the nearest for every one of them :

double round(double a);
float roundf(float a);
long double roundl(long double a);

Rounding up to the nearest multiple of a number

This works for positive numbers, not sure about negative. It only uses integer math.

int roundUp(int numToRound, int multiple)
{
if (multiple == 0)
return numToRound;

int remainder = numToRound % multiple;
if (remainder == 0)
return numToRound;

return numToRound + multiple - remainder;
}

Edit: Here's a version that works with negative numbers, if by "up" you mean a result that's always >= the input.

int roundUp(int numToRound, int multiple)
{
if (multiple == 0)
return numToRound;

int remainder = abs(numToRound) % multiple;
if (remainder == 0)
return numToRound;

if (numToRound < 0)
return -(abs(numToRound) - remainder);
else
return numToRound + multiple - remainder;
}

How do I round an integer down to the nearest multiple of a number?

I'm trying to round an integer to the nearest multiple of a number.
[...]
Is there a more efficient way to do this than x -= (x % the_number)?

In the general case, no. There are alternatives with similar efficiency, such as

x = (x / the_number) * the_number

, but you're not going to do it with fewer than two arithmetic operations. (Also - is more efficient than * on some architectures, and / and % generally are about equivalent in efficiency).

If you want to truncate to a known-in-advance power of 2, however, then you can do it by masking off the lower-order bits with a single bitwise &. For instance, to truncate to the nearest lower multiple of 16 (== 0x10), you could write

x &= ~0xf;  // truncate an int x to a multiple of 16

Is there a function to round a float in C or do I need to write my own?

As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:

#include <stdio.h>
#include <stdlib.h>

int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
return 0;
}

If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);

conver = conver*10.0f;
conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
conver = conver/10.0f;

//If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
//conver = roundf(conver*10.0f)/10.0f;

printf("conver is now %f\n",conver);
return 0;
}

I doubt this second example is what you're looking for, but I included it for completeness. If you do require representing your numbers in this way internally, and not just on output, consider using a fixed-point representation instead.

Rounding up to next power of 2

Check the Bit Twiddling Hacks. You need to get the base 2 logarithm, then add 1 to that. Example for a 32-bit value:

Round up to the next highest power of 2

unsigned int v; // compute the next highest power of 2 of 32-bit v

v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;

The extension to other widths should be obvious.



Related Topics



Leave a reply



Submit