È necessario convertirlo in una stringa e utilizzarlo per la stampa. Non c'è modo per un flusso di stampare un punto mobile senza uno zero iniziale, se ce n'è uno.
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;
}
Provalo online!
MODIFICA: Qualche soluzione che potrebbe piacere di più sarebbe un tipo di flottante personalizzato. per esempio.
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;
};
Provalo online!
convertirlo in una stringa, rimuovere il 0, stampare la stringa. – Brandon