Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting int to int64, int variable still returning negative at int.MaxValue

Tags:

c#

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.

like image 782
RamenNoodles Avatar asked Feb 26 '13 17:02

RamenNoodles


2 Answers

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);
like image 54
Jim Dagg Avatar answered Oct 05 '22 09:10

Jim Dagg


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.

like image 42
ken2k Avatar answered Oct 05 '22 09:10

ken2k