0

I am attempting to generate a percentage value based on the value of a unit (sharePriceCAD) and total value (portfolioValue). To generate the value, I divide the sharePriceCAD by the portfolioValue. However, if I attempt to reverse that calculation and multiple the value by the portfolioValue, I get a different number.

I am looking for a solution to generate the exact same number in both cases. This is in the context of a financial application, so imagine wanting to buy 1 share at 381.26 USD with a USDCAD pair of 1.26951.

Precision is of the utmost importance here, as I need to ensure that I can balance these transactions upon reconciliation. I may have to change the implementation of this system, but I am wondering how I could possibly produce the reversed value with a portfolio value of 1000000000 and a unit price of 381.26 * 1.26951.

How can I always ensure that isEqual === true ? Open to all answers and libraries. Preferably TypeScript friendly as I tried number.js but it does not work out of the box in my TypeScript app.

const portfolioValue = 1000000000
const usdCad = 1.26951;
const cadCash = portfolioValue * 0.4;
const usdCash = portfolioValue * 0.6;
const sharePriceUSD = 381.26;
const sharePriceCAD = sharePriceUSD * usdCad;
const weightOfOneUnit = sharePriceCAD / portfolioValue;
const reversed = weightOfOneUnit * portfolioValue
const isEqual = sharePriceCAD === reversed;
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38
  • 2
    Doing "money math" with JavaScript numbers is a really bad idea. In some modern JavaScript environments, you can make use of "big integer" math, which is less than optimal. You can also look around for "big decimal" libraries. Basic floating-point math is intended for scientific computation, not money. – Pointy Jan 11 '21 at 17:31
  • 1
    See also: https://stackoverflow.com/questions/16742578/bigdecimal-in-javascript – T.J. Crowder Jan 11 '21 at 17:43
  • You know that some numbers don't divide evenly with decimals, like if you were doing this operation manually and you had to write down exact values if sharePriceCAD = 10 and portfolioValue = 30, you'll end up writing a lot of threes after a decimal point, forever. So, you can't exactly represent the calculation using regular decimals and paper. Neither can a computer. Unless you round. That's the key, appropriate use of rounding and precision. – James Jan 11 '21 at 17:54

0 Answers0