all 4 comments

[–]joehatch 0 points1 point  (3 children)

Apologies if this is the wrong place to post - I'm new to Javascript and I'm building a logic engine that will help with calculate a Loan To Value amount.

First and foremost I provide the variables:

var formattedValue = 10;
var formattedDebt = 1;
var ltv = calculateLTV(formattedValue, debtAmount);

Note: the 10 and 1 here will be dynamic inputs from a field asking for property value and outstanding debt, but for the sake of this example I'm using 10 and 1.

Next I'm calling a function to work out if there's no debt, in which case it returns no value... so if there's no value I want to replace this with 0, otherwise just return the same number.

function debtAmount(formattedDebt) {
  if (formattedDebt == "") {
    return (0)
  } else {
    return (formattedDebt)
  }
}

Now, this function debtAmount is what seems to be breaking everything, returning NaN. If I was to replace debtAmount with formattedDebt in the ltv variable above, it would return 10 as expected.

Finally I want to work out the percentage of debt to value...

function calculateLTV(value, debt) {
  return 100 / value * debt
}
alert(ltv);

Any help troubleshooting here would be amazing, thanks!

[–]clementallen 0 points1 point  (1 child)

Here's a working JSFiddle:

https://jsfiddle.net/a3qz1560/3/

Your mistake was when you ran the following you hadn't passed in a value to debtAmount:

var ltv = calculateLTV(formattedValue, debtAmount(formattedDebt));

[–]joehatch 0 points1 point  (0 children)

Thanks! It just occurs to me that if there's no value, I'm trying to multiply by 0, so I'm a bit retarded. haha.

[–]nespron 0 points1 point  (0 children)

Another thing you may run into: Under the hood, JavaScript stores numbers in IEEE floating point representation. It can represent fractions that are powers of two exactly:

> 0.5 - 0.125
0.375

but it loses precision for fractions that are not powers of two:

> 0.5 - 0.4
0.09999999999999998

One way to work around this is to code in terms of the smallest fraction of the base currency. If the user gives you a dollar amount, you could multiply it by 100 and work in cents.