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.
just to add, if you require a specific precision (I noticed your output was set to 8 decimal places) you can use
Another built-in alternative is Decimal.Divide:
More to write, but pretty explicit I'd say.
try:
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 adecimal
, like this:1.0M / estimatedLife
.estimatedLife is an int, isn't it. Try this:
or use SwDevMan81's suggestion:
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:
so 1.0M means "a literal of type decimal with the value 1.0"