2

I want to round a float number.

in python, i have:

round(x, 2)  # 3.1415 -> 3.14

but in c++, i find round function can only round to integer.

Is there any similar method in c++?

nick
  • 832
  • 3
  • 12
  • Do you really want to round it or merely display it so it looks rounded? – user4581301 May 13 '21 at 03:50
  • @user4581301 really want to round it. – nick May 13 '21 at 03:50
  • 1
    Rounding came late to C++, partly because mathematically rounding of floating point numbers to decimal values doesn't exist (at least not in a world of binary representation). Also remember floats are imprecise, so your 3.14 is probably going to look like 3.1.3999999997. Cheap hack: Multiply by 100, round, divide by 100. Have you considered using [fixed point arithmetic](https://en.wikipedia.org/wiki/Fixed-point_arithmetic)? – user4581301 May 13 '21 at 04:00
  • Does this answer your question? [C++ round a double up to 2 decimal places](https://stackoverflow.com/questions/25925290/c-round-a-double-up-to-2-decimal-places) – SuperStormer May 13 '21 at 04:03
  • That's a close dupe, but pay special attention to the "up". – user4581301 May 13 '21 at 04:06

2 Answers2

2

You can use the built-in round functions and some scientific notation.

#include <cmath>
#include <iostream>
using namespace std;

int main()
{
  float x = 3.14159;
  int val = 2;
  x = round(x * pow(10, val)) / pow(10, val);
  cout << x << endl;
  return 0;
}
h0tst3w
  • 114
  • 4
1

AFAIK the standard library provides no such function, but it shouldn't be too hard to roll out your own:

#include <iostream>
#include <cmath>

// fast pow for int, credit to https://stackoverflow.com/a/101613/13188071
int ipow(int base, int exp)
{
    int result = 1;
    while (true)
    {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        if (exp == 0)
            break;
        base *= base;
    }

    return result;
}

double round_prec(double n, int prec)
{
    return std::round(n * ipow(10, prec)) / ipow(10, prec);
}

int main()
{
    std::cout << round_prec(3.1415, 2) << '\n';
}

Output:

3.14

This is, however, a bit of a roundabout way of doing it, there's probably a better way that I don't know of.

mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33
  • Did better than I expected: https://ideone.com/uV0lyc – user4581301 May 13 '21 at 04:05
  • This will work well for numbers close to 0, (like 3) and small amounts of decimal places (like 2). But I'd like to mention that It's precision quickly deteriorates as either of the two parameters grows. – Lukas-T May 13 '21 at 06:23