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

蓝咒 提交于 2019-12-07 03:08:09

问题


How can I make my program output a number with at least one number behind the decimal mark C++? Output: 1 = 1.0 or 1.25 = 1.25 or 2.2 = 2.2 or 3.456789 = 3.456789

Thanks in advance


回答1:


Use showpoint to force the decimal point to be printed

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

It will be followed by the number of 0 required to satisfy the precision of the stream.




回答2:


#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:


If you're going to call this function a lot, then this probably isn't what you're looking for because this isn't the best way to do it, but it does work.

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";
}



回答4:


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");
}


来源:https://stackoverflow.com/questions/18645778/c-how-to-output-number-with-at-least-one-number-behind-the-decimal-mark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!