2

With this code (QtyShipped and QtyOrdered are ints, _percentageOfQtyShipped is a double):

_percentageOfQtyShipped = frbdcbl.QtyShipped / frbdcbl.QtyOrdered;

...I was getting some "div by 0" errors, so I refactored it to this:

double _percentageOfQtyShipped = 0.0;
if ((frbdcbl.QtyShipped != 0) && (frbdcbl.QtyOrdered != 0))
{
    _percentageOfQtyShipped = frbdcbl.QtyShipped/frbdcbl.QtyOrdered;
}

...but now I get the warning from Resharper, "Possible loss of fraction"

However, contrary to Resharper's usual methodology, it does not offer a way to fix it (instead of a yellow light bulb in the gutter of the flagged line of code, I get a grey wrench); so what change need I make to this code to prevent a "possible loss of fraction"?

UPDATE

I used Secret Agent Man #1666620's code, and multiplied by 100 to get vals such as 62.5 instead of 0.625, like so:

double _percentageOfQtyShipped = 0.0;
if ((frbdcbl.QtyShipped != 0) && (frbdcbl.QtyOrdered != 0))
{
    _percentageOfQtyShipped = (frbdcbl.QtyShipped / (double)frbdcbl.QtyOrdered)*100;
}
1
  • 2
    @M.kazemAkhgary from the first line of the question - "QtyShipped and QtyOrdered are ints, _percentageOfQtyShipped is a double" Commented Dec 10, 2015 at 16:59

1 Answer 1

10

When you divide two ints, the result will also be an int, so you lose the fraction. The resulting integer value is then assigned to your double. To get around this, you need to cast one of the ints to a double.

_percentageOfQtyShipped = frbdcbl.QtyShipped/(double)frbdcbl.QtyOrdered;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.