How to return as float when multiplying integer by float?

Hi guys,
I was doing an assignment for my oop class and needed help. My assignment is about creating an invoice program that calculates the invoice amount from taking the item quantity and price and multiplying them together. The quantity as of type integer while the price is of type float as requested in the question. The problem is when I return the invoice amount from multiplying the two i get them as an integer rather than as a float. Another problem is that even when i set the price to 100.00, it displays it as 100. The following is the implementation file. I even tried using the static_cast<float>() thing but its still not working. Any help is appreciated. Thanks.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include "Invoice.h"
using namespace std;

Invoice::Invoice(int number, int quantity, float price)
{
	itemNumber = number;
	
	if (quantity >= 0)
	{
		itemQuantity = quantity;
	}
	else
	{
		quantity = 0;
		cout << "Invalid quantity input. Quantity is set to 0." << endl;
		itemQuantity = quantity;
	}
	
	if (price >= 0)
	{
		pricePerItem = price;
	}
	else
	{
		price = 0;
		cout << "Invalid price. Price is set to 0." << endl;
		pricePerItem = price;
	}
}
void Invoice::printInvoice()
{

	cout << "Item number is " << itemNumber << endl;
	cout << "Quantity is " << itemQuantity << endl;
	cout << "Price per item is " << pricePerItem << endl;
	cout << "Invoice amount is " << getInvoiceAmount() << endl;
}
int Invoice::getInvoiceAmount()
{
	return (static_cast<float>(itemQuantity)*pricePerItem);
}
Last edited on
The return type of your getInvoiceAmount function is of type int, whereas you intend to return as float. Change your function definition to:

 
float Invoice::getInvoiceAmount()


Otherwise, the compiler will automatically cast your float back to an int before returning the value. Returning it as a float should solve your problem.
Just make the return type of the function float. An int multiplied by a float will give a result of type float, it is what you do next that matters.
1
2
3
4
float Invoice::getInvoiceAmount()
{
    return itemQuantity*pricePerItem;
}

Another problem is that even when i set the price to 100.00, it displays it as 100

try cout << fixed << setprecision(2);
(needs #include <iomanip>)
Last edited on
Thanks it works! But shouldnt it automatically take it as a float as it returns it as a float?

1
2
3
4
float Invoice::getInvoiceAmount()
{
	return (itemQuantity*pricePerItem);
}
Last edited on
But shouldnt it automatically take it as a float as it returns it as a float?

What is 'it'? If you mean cout, then the answer is, it does. It simply prints the value using the default settings. Since the default doesn't suit your needs, you need to specify what settings you would like.
Topic archived. No new replies allowed.