c ++ cout <<小数点前不要打'0'

use*_*558 6 c++ decimal number-formatting

我没有找到解决方案,在小数点前没有'0'的情况下写十进制数低于1.我希望以这种格式显示数字:".1",".2"等...

使用:

std::cout << std::setw(2) << std::setprecision(1) << std::fixed << number;
Run Code Online (Sandbox Code Playgroud)

总是给我"0.1","0.2"等格式......

我错了什么?谢谢你的帮助

NaC*_*aCl 5

您需要将其转换为字符串并将其用于打印.如果存在,则流无法在没有前导零的情况下打印浮点.

std::string getFloatWithoutLeadingZero(float val)
{
    //converting the number to a string
    //with your specified flags

    std::stringstream ss;
    ss << std::setw(2) << std::setprecision(1);
    ss << std::fixed << val;
    std::string str = ss.str();

    if(val > 0.f && val < 1.f)
    {
        //Checking if we have no leading minus sign

        return str.substr(1, str.size()-1);
    }
    else if(val < 0.f && val > -1.f)
    {
        //Checking if we have a leading minus sign

        return "-" + str.substr(2, str.size()-1);
    }

    //The number simply hasn't a leading zero
    return str;
}
Run Code Online (Sandbox Code Playgroud)

在线尝试!

编辑:你可能更喜欢的一些解决方案是自定义浮点类型.例如

class MyFloat
{
public:
    MyFloat(float val = 0) : _val(val)
    {}

    friend std::ostream& operator<<(std::ostream& os, const MyFloat& rhs)
    { os << MyFloat::noLeadingZero(rhs._val, os); }

private:
    static std::string noLeadingZero(float val, std::ostream& os)
    {
        std::stringstream ss;
        ss.copyfmt(os);
        ss << val;
        std::string str = ss.str();

        if(val > 0.f && val < 1.f)
            return str.substr(1, str.size()-1);
        else if(val < 0.f && val > -1.f)
            return "-" + str.substr(2, str.size()-1);

        return str;
    }
    float _val;
};
Run Code Online (Sandbox Code Playgroud)

在线尝试!