Setting the precision of numeric data is a little more complicated in C++ than in some other languages.
First you, will need to include iomanip
as a library to use some of these modifiers.
A common method is to pass in stream manipulators to the stream to get numbers for format correctly.
double amount = 12681.34;
double INTEREST_RATE = 0.005;
double interest = amount * INTEREST_RATE;
cout << "The interest earned is: " << fixed << setprecision(2) <<
interest << endl;
Some of the modifiers you can use to format data in the stream include:
Name | Description |
---|---|
fixed | displays the floating point number in fixed point notation so it won’t use scientific notation |
setprecision(n) | sets the precision of the floating-point number to the number assigned by n |
showpoint | Show the decimal and trailing zeros in a floating point number if there are trailing zeros |
setw(width) | specifies the width of the print field |
left | justifies the output to the left, like is normally found with text |
right | justifies the output to the right, makes aligning numbers in columns easier |
Formatting Output in C++ was originally found on Access 2 Learn