-3

I calculate a value out of 3 values to make a selection from a list:

var applicable = from b in discounts.ToList() where
    (b["Interest Rate"].Cast<double>() + 
    (-b["Discount/Premium"].Cast<double>()) + 
    ((-b["Discount/Premium"].Cast<double>()) / (b["Term"].Cast<int>() / 12))) >= GlobalVar.minRealReturn 
    select b;

When I take the first element of "applicable" I receive an element which shouldn't be in the list (I check for elements with a result over 14 . yet this element got an result of 13.975)

enter image description here

Julian Bechtold
  • 167
  • 1
  • 12
  • Is `b` a dictionary? – Dido Aug 09 '17 at 12:00
  • no, b is an arevariable "Row" from excelsheet when using decimal i recieve the errormessage "the ´+´ operator cannot be used with type decmal and double. I swapped all double with decimal – Julian Bechtold Aug 09 '17 at 12:07
  • You should refactor your code to make it more readable. Use models with properties instead of dictionaries whose entries you need to look up by name and then cast. Are you sure `applicable` will always return a value? If it doesn't, you'll get an exception. – Dido Aug 09 '17 at 12:07
  • I cannot use properties since they are loaded from the excel sheets headers. also I made sure to have exception handling. however, i cannot initialize GlobalVar.minimumInterestRate with 14.12 for example. are you sure, decimal handles double precision values (or with more decimal places)? – Julian Bechtold Aug 09 '17 at 12:18
  • 1
    `it should check for 14% and above.` Where is the code that checks for 14% and above? What is the value of `minRealReturn`? – mjwills Aug 09 '17 at 12:20
  • @mjwills the Value of minRealReturn is 14 the code that checks for 14% is the first bit "var applicable = from..." i am using strings in the first part to use "properties" as Dido mentioned. I cant use use them in the second part since this is a linqtoexcel method and the properties are generated in runtime. the compiler wont accept properties since they are not there yet. – Julian Bechtold Aug 09 '17 at 12:31
  • does it change the outcome of my question? – Julian Bechtold Aug 09 '17 at 12:37

1 Answers1

1

The main issue is likely that:

b["Term"].Cast<int>() / 12

doesn't do what you think it does.

Let's say that b["Term"].Cast<int>() was 18. You might expect that 18/12 would result in 1.5. But it doesn't. It results in 1 - since you are doing integer division.

As such, you likely need to change the code to:

b["Term"].Cast<int>() / 12D

Since that will force it not to use integer division. You may alternatively be able to convert the Cast<int> to Cast<double>.

mjwills
  • 23,389
  • 6
  • 40
  • 63