I was working on a praxctice program and wanted some numbers fixed dollar amounts to 2 decimal places while others to be displayed as plain old ints. I used this code, but noticed that now ALL numbers are set as fixed 2 place decimals. Is this how fixed and setprecisioun are supposed to work, or is it only supposed to effect the line of code they are associated with:

    cout << endl << endl << endl;
    cout << "Loan Amount $" << fixed << setprecision(2) << loan << endl;
    cout << "Monthly Interest Rate: " << rate << "%" << endl;
    cout << "Number of Payments: " << payments << endl;
    cout << "Monthly Payment $" << setprecision(2) << payment << endl;
    cout << "Amount Paid Bacl $" << setprecision(2) << endl;

This code gives me something like:
%12.00 (I expected %12)
36.00 (once again expecting 36)
blah blah blah

you get the point, I don't think I'm understaning how these formatting commands work, the books don't seem to say anything on their scope.

4 Years
Discussion Span
Last Post by mixelplik

setprecision just does what it says. It sets the precision to 2 figures after the decimal point and it will stay that way.


setprecision() is in effect until you call the funcion to change the value for floats and doubles. Assuming rate is either float or double, on line 3 call setprecision(0) to not display any decimals. Then on line 4 you have to call setprecision(2) again.

Edited by Ancient Dragon


Thanks guys! I was wondering, I thought so, this makes it clear!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.