Jonathan Layduhur
Jonathan Layduhur

Reputation: 93

Double vs float precision issue

#include <iostream>

int main()
{
    double a = 2 , b = 3;

    double answer = a/b;
    std::cout << answer;
    std::cout << std::to_string(answer);
}

Float or double I get : 0.666667;

I was expected more precision from the double ; How do i get something more like : 0.666666666666667

Edit : and i need to not lose the precision by using to_string;

Upvotes: 0

Views: 130

Answers (2)

AngryParticle
AngryParticle

Reputation: 1539

The setprecision is in the header file #include<iomanip> which will let you set the decimal precision.

For example:

#include <iostream>
#include <iomanip>  // The precision manipulator is in this header file 

int main()
{
    double a = 2 , b = 3;

    double answer = a/b;
    std::cout << std::setprecision(15) << answer;
    return 0;
}
 

Upvotes: 0

eerorika
eerorika

Reputation: 238281

I was expected more precision from the double

The precision of a floating point type is separate concept from the precision of a decimal number in textual representation.

You didn't specify the precision that you want, so default was used. It just so happens that the default isn't what you arbitrarily expected. You can specify the precision for example like this:

std::cout.precision(15);

Upvotes: 2

Related Questions