C ++ cout << do not print '0' before decimal point

I did not find a solution to write a decimal number below 1 without "0" to the decimal point. I want to display numbers in 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.

How am I wrong? Thank you for your help.

+6
source share
2 answers

You need to convert it to string and use for printing. There is no way for a stream to print floating point without a leading zero, if any.

 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 that you might like more would be a special type of float. eg.

 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 !

+4
source

In iomanip library does not seem to have the function of trimming 0 to cout . You need to convert the output to a 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; 
0
source

Source: https://habr.com/ru/post/977573/


All Articles