Search code examples
c++doublevisual-c++

Decimals not displaying when using Float or Double type


My code is this:

#include <iostream>

int main()
{
    using namespace std;

    const float dollar = 1.00;

    cout << "You have " << dollar*10.00 << " dollars." << endl;

    cin.get();
    cin.get();

    return 0;
}

I am a beginner to C++. I typed this code just playing around and assumed that the console would display "You have 10.00 dollars, but it actually displays that I have "10" and not "10.00" dollars. Why is this?


Solution

  • Since you are dealing with dollar amounts, you can set the following before writing to cout:

    std::cout.precision(2);
    std::cout.setf(std::ios::fixed);
    

    Live code example at coliru

    #include <iostream>
    
    int main() {
        using namespace std;
        const float dollar = 1.00;
        std::cout.precision(2);
        std::cout.setf(std::ios::fixed);
        cout << "You have " << dollar*10.00 << " dollars." << endl;
        cin.get();
        cin.get();
        return 0;
    }