If I give a double value and an integer value, I want to round that double to the precision of the integer value accurately. In the end, I want to get a double value which is more accurate as the output.
I tried it using the boost multi-precision library like the one below.
#include <boost/multiprecision/cpp_dec_float.hpp>
int main() {
double input = 7.7778
int precision = 3;
using my_dec_100 = boost::multiprecision::cpp_dec_float_50;
double intpart, fracpart;
fracpart = modf(input, &intpart);
int decimalLength = 0;
if (fracpart > 0){
decimalLength = std::ceil(-std::log10(std::pow(10, -std::numeric_limits<double>::digits10) * fracpart));
}
double rounded = std::floor(input * std::pow(10, precision) + 0.5) / std::pow(10, precision);
my_dec_100 f11(my_dec_100(rounded * std::pow(10, decimalLength)) / std::pow(10, decimalLength));
double output = f11.convert_to<double>();
std::cout << std::setprecision(precision) << std::fixed << output << std::endl;
return 0;
}
But I am not sure whether this is working for each and every value. I want to work this even for a long fractional part also. ex:- 7.1346745428482672454818495 Also, here I have used the boost library to create f11 only. Is there any other way I can achieve this functionality using the boost multi-precision library?