Correct Decimal Calculations in JavaScript
Some decimal calculations will give seemingly strange results like so:
console.log(0.1 + 0.2); // 0.30000000000000004
This is not actually a bug, it is do with with JavaScript's Number implementation which is using a Base 2 system instead of a Base 10 one. You can read more about that here. Anyways, the simplest way to deal with this is to always ensure you are working with integers. To fix the above example:
const result = ((0.1 * 10) + (0.2 * 10)) / 10; console.log(result); // 0.3
Although once you start moving beyond basic calculations this becomes increasingly difficult, especially when involving multiplication. For example, here is an attempt at getting the total compound interest after a set number of years:
function getTotalCompoundInterest(interest, years) { const epsilon = 10000; return Math.pow(interest * epsilon, years) / Math.pow(epsilon, years); } console.log('\nCorrect Compound Interest Calculation'); console.log(getTotalCompoundInterest(1.10, 5)); // 1.61051 console.log(getTotalCompoundInterest(1.12, 5)); // 1.7623416832000016 console.log(getTotalCompoundInterest1(1.1273, 5)); // 1.8205287217241934
I was able to make the first interest rate convert to a decimal, but not the second. A more complex calculation will be needed to fix that. Instead a library that does computations in Base 10 should be used. Here is an example with decimal.js:
const Decimal = require('decimal.js'); function getTotalCompoundInterest(interest, years) { return new Decimal(interest).toPower(years).toNumber(); } console.log(getTotalCompoundInterest(1.10, 5)); // 1.61051 console.log(getTotalCompoundInterest(1.12, 5)); // 1.7623416832 console.log(getTotalCompoundInterest2(1.1273, 5)); // 1.8205287217241937
Notice how the last value for this calculation is actaully correct unlike the original strategy which could not have been corrected even with rounding.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/decimalOperations.js











