AngryDuck
AngryDuck

Reputation: 4607

How to properly print a double to cout in C++

I've had a look at some questions before posting this and couldn't find what I was looking for, so if it's a duplicate I'm sorry.

I have this code:

cout << "The balance at year " << i << " will be " << char(156) << std::setprecision(2)
     << balance << endl;

To my knowledge this should print to the console something like:

£2.00
£100.46

*fyi Above are just examples I know there's nothing to suggest those numbers, but the format should look like that, right?

But here's my output:

£1e+002
£1.1e+002

Why is it doing this?

It was my understanding that using setprecision would show 2 decimal places and nothing more.

Oh and also noticed hardly any questions about printing doubles that said use setprecision actually state that this needs including:

#include <iomanip>

Upvotes: 2

Views: 6495

Answers (3)

A human being
A human being

Reputation: 1220

Do it like this:

cout << "The balance at year " << i << " will be " << char(156) << std::setprecision(2) << std::fixed << balance << endl;

Upvotes: 2

lcs
lcs

Reputation: 4245

Use std::fixed to set fixed format, rather than scientific notation.

cout << "The balance at year " << i << " will be " << char(156) << std::setprecision(2) << std::fixed << balance << endl;

Upvotes: 3

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

setprecision sets the precision, number of digits.

fixed sets fixed format.

i bet that'll fix it.

Upvotes: 5

Related Questions