I'm trying to display the price of an item. The price is multiplied by the item quantity.
int itemCost = itemPrice * itemQuanity;
When the quantity of the item becomes too much, the itemCost goes into negatives, meaning I need a larger int, so I changed the int to use int64.
int64 itemCost = itemPrice * itemQuantity;
With this change it still outputs a negative itemCost, what am I doing wrong?
I tried using
System.Convert.ToInt64(int value);
but that doesn't seem to work either, still getting a negative number when reaching int.MaxValue.
What types are itemPrice
and itemQuantity
? If they're both int
, you're going to get an int
(32-bit) as an answer from the multiplication, which you're then storing in an int64
. At that point, the conversion (and overflow) has already happened, and casting to an int64
won't help.
You need to ensure both operands are int64 before you multiply. So if they aren't already,
int64 itemCost = ((int64) itemPrice) * ((int64) itemQuantity);
You could try:
long itemCost = (long)itemPrice * (long)itemQuantity;
What happened is that you still tried to multiply two int
, even if you stored the result in a long
. Cast them to long
first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With