Amit Anchalia
Amit Anchalia

Reputation: 3

Print a decimal number in a particular format using setfill() in c++

I am trying to print a decimal no. in following format : "#####+3.01" Case: There is a decimal no (let say 3.01 in this case). I have to print it with its sign +/- preceding with y no. of #, with some fix total width. (let say x = 10 in this case).

I tried do something like this :

   double no = 3.01;
   cout << setfill('#') << setw(10) ;
   cout << setiosflags(ios::showpos);
   cout << fixed << setprecision(2) << no << endl;

But i am getting followinfg output :

    +#####3.01

Expected Output :

    #####+3.01

Upvotes: 0

Views: 343

Answers (1)

Arash
Arash

Reputation: 2164

Your code gave me correct result. I am using a Linux machine.

Just in case it is a OS dependent problem, try this code:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    double no = 3.01;
    cout << setfill('#') << std::right<< setw(10) ;
    cout << setiosflags(ios::showpos);
    cout << fixed << setprecision(2) << no << endl;
}

Upvotes: 1

Related Questions