How to format numbers?

Hey guys, I would like to make a program that asks a user to input a number (float) and I'll show that number to the user with a precision of two decimal places.

For exmaple, if a user enters 15. My program will show an output of 15.00

But if the user enters 15.151, then my program will only show 15.15

How can I program my program to be like this?

Are you using printf() or cout ? The solution depends on your code.

For C++,
See http://www.cplusplus.com/reference/iomanip/setprecision/
and also http://www.cplusplus.com/reference/ios/fixed/
Last edited on
I use something like:

 
cout<<iVar;


I still don't get it. Can someone explain it to me more thoroughly?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <iomanip>

using namespace std;

int main() 
{
    double a = 15.151;
    double b = 15.157;
    double c = 6.3;
    
    cout << "Default:\n";
    cout << setw(10) << a << setw(10) << b << setw(10) << c << endl;
    
    cout << "\nTwo significant figures:\n";
    cout << setprecision(2);
    cout << setw(10) << a << setw(10) << b << setw(10) << c << endl;

    cout << "\nTwo decimal places;\n";
    cout << fixed;
    cout << setw(10) << a << setw(10) << b << setw(10) << c << endl;
}

Default:
    15.151    15.157       6.3

Two significant figures:
        15        15       6.3

Two decimal places;
     15.15     15.16      6.30


setw() was used simply to set the field width for a neat output.

cout.precision() and cout << setprecision() are alternative ways to do the same thing.

fixed changes the meaning and behaviour of the precision figure

Last edited on
I've used a code that works:

1
2
3
cout.setf( std::ios::fixed, std:: ios::floatfield );
cout.precision(5);


Can I know what the setf and floatfield is for?
Can I know what the setf and floatfield is for?
Well, the starting point is to read up on what the reference pages have to say:
http://www.cplusplus.com/reference/ios/ios_base/setf/
http://www.cplusplus.com/reference/ios/ios_base/fmtflags/

In the example you gave, the ios::floatfield specifies a group of flags. It is passed as the second parameter, the mask field. Only the flags which are part of that group will be affected by the call to setf()

There are just two flags in the group. One, both or none of these may be set:
1
2
ios::fixed
ios::scientific

It's easy to get in a tangle when trying to understand bit flags. One way of looking at this code
 
cout.setf( std::ios::fixed, std:: ios::floatfield );
is to think of it as first clearing all of the flags belonging to the mask (that is set both fixed and scientific off) and then set on the fixed flag.

Topic archived. No new replies allowed.