math not showing 2 digits

I am trying to multiply two numbers

short totalSharesPurchased = 1024,
stockPurchasePrice = 39034.88,
stockSalePrice = 22374.40;

short gain_loss_amount = stockSalePrice - stockPurchasePrice;

I need the output 'cout' to show 2 decimal places. I think this is related to type of variables declared. Thoughts?
Thanks
You defined floating point numbers as integers of type short, So the numbers have no fractional parts. You should declare them as float or double.
Do you mean something like this:

1
2
3
4
5
6
7
8
9
10
#include <iomanip>
#include <iostream>

int main()
{
        float x = 5.4321;
        std::cout << setprecision(2) << x << std::endl;

        return 0;
}
I tried making float and double, then the math round up so instead of 39034.88 I get 39034.9 in the answer.

Last edited on
1
2
3
4
5
6
double stockPurchasePrice = 39034.88;
double stockSalePrice = 22374.40;
 
double gain_loss_amount = stockSalePrice - stockPurchasePrice;

std::cout << std::fixed << std::setprecision( 2 ) << gain_loss_amount << std::endl;


The output is:

-16660.48

That looks good. New to c++ and in beginning class so have not leaned that yet but can not believe there is not a simpler way... Thank you!!!
Topic archived. No new replies allowed.