In my code I want to have a function which performs some calculations based on boost::multiprecision::cpp_dec_float_100 and returns string as a result with some precision, but the question is how I should set the precision ? e.g. If the precision is 9, then I expect the following results for the following numbers:
for 2345.12345678910111213
I expect string "2345.123456789"
but I have 12345.1235
for 1.12345678910111213
I expect string "1.123456789"
but I have 1.12345679
So it always returns my exact number of characters provided to str() function with round. I know that I can do it like e.g. this:
std::stringstream ss;
ss << std::fixed << std::setprecision(9) << my_value;
return ss.str();
or use cout(but this is not my case) or do some find on string to find "." and take only 9 characters after it, but can I do it in an easier way ? maybe in boost is some function to do it correctly ?
#include <iostream>
#include <boost/multiprecision/cpp_dec_float.hpp>
namespace bmp = boost::multiprecision;
std::string foo_1()
{
bmp::cpp_dec_float_100 val{"12345.12345678910111213"};
return val.str(9);
}
std::string foo_2()
{
bmp::cpp_dec_float_100 val{"1.12345678910111213"};
return val.str(9);
}
int main()
{
auto const val_1 = foo_1();
auto const val_2 = foo_2();
std::cout << "val_1: " << val_1 << std::endl;
std::cout << "val_2: " << val_2 << std::endl;
return 0;
}
online version: https://wandbox.org/permlink/HTAHsE5ZE3tgK9kf
CodePudding user response:
Change the line:
return val.str(9);
To:
return val.str(9, std::ios::fixed);
You will get the expected strings.