问题
I didn't find the solution to write decimal number inferior to 1 without the '0' before the decimal point. I want to display numbers at this format : ".1", ".2", etc...
using :
std::cout << std::setw(2) << std::setprecision(1) << std::fixed << number;
always give me formats like "0.1", "0.2", etc...
What do I wrong ? Thanks for your help
回答1:
You need to convert it to a string and use it for printing. There is no way for a stream to print a floatingpoint without a leading zero, if there is one.
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;
}
Try it online!
EDIT: Some solution you may like more would be a custom float type. e.g.
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;
};
Try it online!
回答2:
In iomanip library, it seems no function to trim 0
before cout
. You need to convert output to string.
Here is my solution:
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;
来源:https://stackoverflow.com/questions/26684939/c-cout-dont-print-0-before-decimal-point