rmurphey / js-assessment-answers

125 stars 84 forks source link

numbers.multiply: adjust function produces incorrect multipliers #16

Open elstgav opened 11 years ago

elstgav commented 11 years ago

Currently, multiply can sometimes produce incorrect results. For instance, multiply(3, 0.123002) returns 0.36900599999999995 instead of the expected 0.369006.

I believe the problem is on Line 35 of numbers.js, where an exponent (i.e. the number of decimal places to overcome) is derived by Math.floor( Math.log(num) * -1 ). This can produce unnecessarily large exponents, or incorrectly small ones in certain cases (e.g. num = 0.123002).

Math.floor( Math.log(21.02) * -1 ) === -4

_(side note: I was surprised to find out that Math.log actually returns ln(x), not log10(x))_

I'd propose finding the exponent by turning the number into a string and counting the decimal places:

var decimals = num.toString().split('.')[1],  // 21.02 => "02"
    exponent = decimals ? decimals.length : 0 // "02".length = 2

Would this be a more appropriate solution?