Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use big.js?

From the examples of big.js they show this example

0.3 - 0.1                              // 0.19999999999999998
x = new Big(0.3)
x.minus(0.1)                           // "0.2"
x                                      // "0.3"

x.div(y).plus(z).times(9).minus('1.234567801234567e+8').plus(976.54321).div('2598.11772')

Which is a very simple example. In my case I would like to calculate

res = a + (b / c) + (d + 1) / (e * f * g);

I cannot see how that can be calculated without introducing 7 temporary variables, which doesn’t seam correct.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Question

Does anyone know how to calculate the above with big.js?

>Solution :

Yes, you can use the plus(), div(), and times() methods in big.js to calculate the expression in the following way:

const res = a.plus(b.div(c)).plus(d.plus(1).div(e.times(f).times(g)));

This uses the plus() method to add a to b / c, then uses the div() method to divide d + 1 by e * f * g, and finally uses the plus() method again to add the result of those two operations together to get the final result.

This approach avoids the need for temporary variables and allows you to use the big.js methods to perform the calculations with arbitrary-precision decimal numbers.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading