1

Below is a simply Math.max statement I'm trying to use in my jQuery app, along with the methods being called.

    guaranteedEoy: function() {
        return this.fixedAllocation() * (1 + (this.attributes.fixedRate / 100)) * Math.pow(1, 6);
    },

    contractVal: function (value) {
        value = parseFloat(value).toFixed(2);
        console.log(value);
        console.log(this.guaranteedEoy());
        console.log(parseFloat(this.guaranteedEoy()) + parseFloat(value));
        console.log(this.attributes.purchasePayment * Math.pow(1.01, 7));
        console.log(Math.max((this.attributes.purchasePayment * Math.pow(1.01, 7)), (this.guaranteedEoy() + value)));
        console.log('   ');
        return Math.max((this.attributes.purchasePayment * Math.pow(1.01, 7)), (this.guaranteedEoy() + value));
    },

I put the console.log statements in there because the number being returned from the Math.max function is exponentially larger than either number it is supposed to be comparing. To illustrate here's a screen print of the console readouts from above:

enter image description here

To simplify here are the values each console readout correspond to

Value: 64000.00
this.guaranteedEoy(): 37008
this.guaranteedEoy() + value: 101008
this.attributes.purchasePayment * Math.pow(1.01, 7): 107213.53521070098
Math.max((this.attributes.purchasePayment * Math.pow(1.01, 7)), (this.guaranteedEoy() + value)): 370086400

So basically the Math.max statement reads

Math.max(107213.53521070098, 101008)

However for some reason it is returning a value of 370086400.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
NealR
  • 10,189
  • 61
  • 159
  • 299

2 Answers2

3

370086400 is concatenation of mentioned values 37008 and 64000.

It should be:

console.log(Math.max((this.attributes.purchasePayment * Math.pow(1.01, 7)),
        (parseFloat(this.guaranteedEoy()) + parseFloat(value))));

Use parseFloat once more to avoid string concatenation (which is occured).

Edit: it looks like value is the String (due to .toFixed()), while this.guaranteedEoy() returns Number. So it is possible that parseFloat only for value will be enough.

Regent
  • 5,142
  • 3
  • 21
  • 35
1

toFixed returns a string, so this.guaranteedEoy() + value, performs string concatenation. If you just want to round the value to two decimal places, see Round to at most 2 decimal places (only if necessary).

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143