【问题标题】:c++ cout << don't print '0' before decimal pointc ++ cout <<不要在小数点前打印'0'
【发布时间】:2014-12-28 09:06:37
【问题描述】:

我没有找到在小数点前没有“0”的情况下写出低于 1 的十进制数的解决方案。 我想以这种格式显示数字:“.1”、“.2”等...

使用:

std::cout << std::setw(2) << std::setprecision(1) << std::fixed << number;

总是给我“0.1”、“0.2”等格式...

我做错了什么? 感谢您的帮助

【问题讨论】:

  • 转成字符串,去掉0,打印字符串。

标签: c++ decimal number-formatting


【解决方案1】:

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

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

试试online

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

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

试试online

【讨论】:

  • 一些改进:(1)使用double,(2)用于负值检查参数是否为负,如果是,则使用-number调用self并添加连字符,(3)用于其余检查字符串结果而不是原始值,(4) 不要使用get 前缀(如getsingetcosgetsqrt、哎哟)。
  • 谢谢大家,这就是我所担心的,我希望有更好的解决方案...我将使用字符串转换。
【解决方案2】:

iomanip 库中,在cout 之前修剪0 似乎没有功能。您需要将输出转换为字符串。

这是我的解决方案:

double number=3.142, n; //n=3
char s[2];
sprintf (s, ".%d", int(modf(number, &n)*10)); 
                     //modf(number, &n)=0.142 s='.1'
cout << s;

【讨论】:

    猜你喜欢
    • 2013-12-06
    • 1970-01-01
    • 2022-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2011-04-02
    相关资源
    最近更新 更多