views:

86

answers:

5

If this was previously talked about, I'm sorry, I had a hard time searching on this.

I am calculating a depreciation rate. One portion of our calculation is 1/life in months. My table stores this data in a decimal field. I tried test = 1 / estimatedLife; but the result of the calculation of test (which is defined as a decimal) is 0.

Say the estimated life is 36 months. So 1/36 should equal 0.02777778.

Any thoughts of what I am doing wrong?

BTW, I changed the test to a double and had the same result.

+4  A: 

try:

test = 1.0M / estimatedLife;
SwDevMan81
What does the "M" do? I did do 1.00 and that worked great! I got a compile error on 1.0M
Mike Wills
The `M` makes it a `decimal`. `1.00` is a `double`, which is less precise.
SLaks
As SLaks said, it makes it a decimal. Here is the documentation: http://msdn.microsoft.com/en-us/library/364x0z75(VS.71).aspx
SwDevMan81
@Mike Wills - What was the compiler error?
SwDevMan81
It must have been due to me forgetting to change test back to decimal from double. It works now.
Mike Wills
@Mike Wills - Ok great
SwDevMan81
+2  A: 

Your code divides two integers, then assigns the result (which is also an integer) to a decimal variable.

You need to switch to decimal division by making at least one of the operands a decimal, like this: 1.0M / estimatedLife.

SLaks
+2  A: 

estimatedLife is an int, isn't it. Try this:

    decimal test = 1 / (decimal) estimatedLife;

or use SwDevMan81's suggestion:

    test = 1.0M / estimatedLife;

The issue is that integer division throws away everything after the decimal point. One of the arguments has to be a decimal for you to get the result you want.

The documentation link that he posted in a comment says:

If you want a numeric real literal to be treated as decimal, use the suffix m or M

so 1.0M means "a literal of type decimal with the value 1.0"

JeffH
+4  A: 

Another built-in alternative is Decimal.Divide:

test = Decimal.Divide(1, estimatedLife);

More to write, but pretty explicit I'd say.

Nick Craver
+1. that's quite elegant
gbn
+2  A: 

just to add, if you require a specific precision (I noticed your output was set to 8 decimal places) you can use

decimal test = Math.Round(1M / estimatedLife,8);
Pharabus