# Vb.Net attempt to divide by zero problem

Hi EE,
I have a piece of code, it's working most of the time, however it some time throw 'attempt to divide by zero' error, although I did have a check for zero on the denominator before the divide, wonder what the problem is, if anyone has any idea please let me know.

``````                            Dim myDenominator As Decimal = (CDec(Math.Round(row("TotQty"), 2)) + CDec(Math.Round(row("DelQty"), 2)))
If (myDenominator <> 0) Then

Dim newStdCost As Decimal = (((CDec(Math.Round(row("TotQty"), 2)) * CDec(Math.Round(row("StdCost"), 2))) + (CDec(Math.Round(row("DelQty"), 2)) * CDec(Math.Round(row("DelCost"), 2))))) / myDenominator

End If``````
Jacques Bourgeois (James Burger)

Do you absolutely need the precision of a Decimal?

When you assign the value to your denominator, you end up with only 2 decimal. And the multiplication ends up with 6 at most. There is no need for all the extras that the Decimal type provides.

Because the number of decimal places in the Decimal type is variable, Decimal values are handled in a special way compared to the more straightforward Single and Double type.

I would try removing all the CDec and work with a Double all the way. Convert only the result to Decimal if you really need that data type for other operations.
miketonny

thanks James,
could you let me know how double and decimal are handled differently? i see this is a good chance of learning something I didn't know before.
Jacques Bourgeois (James Burger)

membership
Create an account to see this answer
Signing up is free. No credit card required.
SOLUTION
ElrondCT

membership
Create an account to see this answer
Signing up is free. No credit card required.
Thanks for the input Elrond.

I never had to deal with those precisions in my applications, where woodworkers often find that 1/64 is too much precision in my current project, and where money operations in my older projects were almost of the multiplying a quantity by a unit price and adding the taxes sort. And my own accoutant is OK as long as we follow the rounding rules of the canadian government that do not got further than a few decimals. My bank does not care either, interests on my 25 years mortgage were rounded out at the 4th decimal.

Having the input from a programmer who has another experience is always a good learning lesson.

thanks guys for all the input, really helped me understand the definition and difference between these two. appreciate all your help.