C ++ How to output a number with at least one number behind the decimal mark

How to make my program print a number with at least one number behind the C ++ decimal mark? Conclusion: 1 = 1.0 or 1.25 = 1.25 or 2.2 = 2.2 or 3.456789 = 3.456789

Thank you in advance

+6
source share
5 answers

Use showpoint to make decimal point print

 double x = 1.0; std::cout << std::showpoint << x << "\n"; 

It will be followed by the number 0 , necessary to ensure the accuracy of the flow.

+4
source
 #include <cmath> #include <iostream> #include <limits> struct FormatFloat { static constexpr const double precision = std::sqrt(std::numeric_limits<double>::epsilon()); const double value; FormatFloat(double value) : value(value) {} void write(std::ostream& stream) const { std::streamsize n = 0; double f = std::abs(value - (long long)value); while(precision < f) { f *= 10; f -= (long long)f; ++n; } if( ! n) n = 1; n = stream.precision(n); std::ios_base::fmtflags flags = stream.setf( std::ios_base::fixed, std::ios_base::floatfield); stream << value; stream.flags(flags); stream.precision(n); } }; inline std::ostream& operator << (std::ostream& stream, const FormatFloat& value) { value.write(stream); return stream; } inline FormatFloat format_float(double value) { return FormatFloat(value); } int main() { std::cout << format_float(1) << '\n' << format_float(1.25) << '\n' << format_float(2.2) << '\n' << format_float(3.456789) << std::endl; return 0; } 
+3
source

If you are going to call this function many times, this is probably not what you are looking for, because this is not the best way to do this, but it works.

Something along the lines of:

 string text = to_string(55); if (text.find(".") != std::string::npos) { cout << "No digit added after decimal point" << text; } else { cout << "Digit added after decimal point" << text << ".0"; } 
+1
source

This should work

 #include <iostream> using namespace std; int main(){ double number; int intnumber; cout << "insert number: "; cin >> number; intnumber = number; if (number == intnumber){ cout.setf(ios::fixed); cout.precision(1); cout << number << endl; } else { cout << number << endl; } return 0; } 
0
source
 double value = ...; std::ostringstream ss; ss.precision(std::numeric_limits<double>::digits10 + 2); ss << value; std::string s = ss.str(); if (s.find('.') == string::npos) { s.append(".0"); } 

or

 double value = ...; std::wostringstream ss; ss.precision(std::numeric_limits<double>::digits10 + 2); ss << value; std::wstring s = ss.str(); if (s.find(L'.') == string::npos) { s.append(L".0"); } 
0
source

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


All Articles