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++?
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++?
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;
}
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.