Zaid Amir
Zaid Amir

Reputation: 4775

c++ rounding special float values to integers

I am having some trouble rounding some special float numbers to integers. I need to round a float number to an integer (if and only if) the first three float point values are zeros or 9's.

For example if the number was 4.0001 I need to round this to 4. and if the number was 4.9998 I need to round it to 5. Other than that, the values should be displayed as they are.

In other words I need to print an integer only if the above two rules were met, otherwise I should print float numbers,

How can one achieve this in C++.

Regards

Upvotes: 0

Views: 210

Answers (2)

James Kanze
James Kanze

Reputation: 153889

If you're interested in the fractional part, modf is your friend. Say something like:

double
conditionallyRound( double original )
{
    double dummy;
    double frac = modf( fabs( original ), &dummy );
    return frac < 0.001 || frac > 0.999
        ? round( original )
        : original;
}

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272447

If x should be rounded, then the maximum difference between x and round(x) will be 0.0001.

Of course, you should be aware that binary floating-point cannot exactly represent 0.0001, so this will always be an approximation.

Upvotes: 2

Related Questions