NealR
NealR

Reputation: 10709

Math.max not returning either number being compared

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.

Upvotes: 1

Views: 71

Answers (2)

Felix Kling
Felix Kling

Reputation: 817208

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).

Upvotes: 1

Regent
Regent

Reputation: 5176

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.

Upvotes: 3

Related Questions