Looking for a function.

So, here's the problem. I've got a happy long double named Fred. He looks like 9.56756785685685682595. I need a function so I can round him down that takes TWO values, not one. The first value is Fred, the second should be how many decimals should remain. For example, round(Fred,0) == 10. round(Fred,3) == 9.568.

If there is no function to do this, how can I do it with existing functions? Note: I prefer to use standard libraries.
Something like the following?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// http://ideone.com/pnINN6
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>

long double my_round(long double value, unsigned decimal_places)
{
    long double mult = std::pow(10, decimal_places);
    return std::round(value * mult) / mult;
}

int main()
{
    long double Fred = 9.56756785685685682595L;
    auto max_prec = std::numeric_limits<long double>::digits10;

    for (unsigned i = 0; i < max_prec; ++i)
    {
        std::cout << "decimal places: " << i << '\n';
        std::cout << std::setprecision(max_prec) << Fred << '\n';
        std::cout << std::setprecision(i + 2) << my_round(Fred, i) << "\n\n";
    }
}
EXACTLY that, thanks a lot. That was pretty clever!

Also, my 256th post celebration! pow(2,8);! That's the size of an 8BIT integer!!
Last edited on
closed account (G1vDizwU)
Thanks guys.
Topic archived. No new replies allowed.