Print a maximum of 4 decimal places

I am trying to print a maximum of 4 digits after a decimal point in C ++ (using streams). So if the number does not need 4 digits after the decimal, I want him to use only the number of decimal places that he really needs.

Examples:

1.12345 -> 1.1234 1.0 -> 1 1.12 -> 1.12 1.12345789 -> 1.1234 123.123 -> 123.123 123.123456 -> 123.1234 

I tried std::setprecision(4) , but this sets the number of significant digits and does not work in the test case:

 123.123456 gives 123.1 

I also tried giving std::fixed along with std::setprecision(4) , but this gives a fixed number of digits after the decimal, even if it is not needed:

 1.0 gives 1.0000 

It seems that std::defaultfloat is the one I need, not fixed or exponential. But it does not seem to print the number of digits after the decimal point and does not have the ability to significant digits.

+5
source share
2 answers

We can do this using std::stringstream and std::string . We pass double to the stream formatting it, as if we were sending it to cout . Then we examine the string that we get from the stream to see if there are trailing zeros. If there is, we will get rid of them. As soon as we do this, we check whether we remain with the decimal point, if we then get rid of it. You can use something like this:

 int main() { double values[] = { 1.12345, 1.0, 1.12, 1.12345789, 123.123, 123.123456, 123456789, 123.001 }; std::vector<std::string> converted; for (auto e : values) { std::stringstream ss; ss << std::fixed << std::setprecision(4) << e; std::string value(ss.str()); if (value.find(".") != std::string::npos) { // erase trailing zeros while (value.back() == '0') value.erase(value.end() - 1); // if we are left with a . at the end then get rid of it if (value.back() == '.') value.erase(value.end() - 1); converted.push_back(value); } else converted.push_back(value); } for (const auto& e : converted) std::cout << e << "\n"; } 

What when creating a running example gives

 1.1235 1 1.12 1.1235 123.123 123.1235 123456789 123.001 
+4
source

Using the answer here , as well as custom logic to remove zeros and periods:

 #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <vector> #include <iterator> #include <algorithm> std::string remove_zeros(std::string numberstring) { auto it = numberstring.end() - 1; while(*it == '0') { numberstring.erase(it); it = numberstring.end() - 1; } if(*it == '.') numberstring.erase(it); return numberstring; } std::string convert(float number) { std::stringstream ss{}; ss << std::setprecision(4) << std::fixed << std::showpoint << number; std::string numberstring{ss.str()}; return remove_zeros(numberstring); } int main() { const float values[]{1.12345, 1.0, 1.12, 1.12345789, 147323.123, 123.123456}; for(auto i : values) std::cout << convert(i) << '\n'; } 

gives:

 1.1235 1 1.12 1.1235 147323.125 123.1235 
+1
source

Source: https://habr.com/ru/post/1261525/


All Articles