Search code examples
c++formattingnumber-formattingcout

How can i change printf("%.2f") in C++


How can i change printf("%.2f") in C++ so that it will also display upto two decimals Using cout

Also for this to change in c++ to have blank space just like in c printf("-6c%14d%20.2f",'A',val1,val2); I have declared val1,val2 in double


Solution

  • for change use header file < iomanip > with setprecision(number of digit to display)

    #include<iostream>
    #include<iomanip>
    using namespace std;
    int main()
    { 
    double a;
    cin>>a;
      cout<<setprecision(4)<<a;
    return 0;
    }
    

    for your 2nd question to have blank space just like that in c++ you can simply use this method with setprecision as your question requires it

     cout<<" "<< 'A'<<"\t\t    "<<val1<<"\t\t     "<<setprecision(4)<<val2<<endl;