1

I was wondering if there was any way to prevent javascript from automatically rounding my numbers. I made a program to calculate pi using the Gregory-Leibniz series. It only goes to a certain amount of decimal places. Here is my code:

pi=0;
x=1;
i=1;
function doStuff(){
    pi = pi+(4/x);
    x=x+2;
    pi = pi-(4/x);
    x=x+2;
    document.getElementById("someDiv").innerHTML = pi;
}
Patrick M
  • 10,547
  • 9
  • 68
  • 101
user3334397
  • 11
  • 1
  • 2
  • 1
    It only goes to a certain number of decimal places because it only *has* a certain number of decimal places. JavaScript math has finite precision, in other words. – Pointy Feb 20 '14 at 19:59

2 Answers2

1

If you are trying to work with numbers requiring precision beyond the JavaScript float (only 64 bits of precision) you could consider using a library like one of those mentioned in this question: Is there a decimal math library for JavaScript?

In particular the bignumber library looks promising for your purposes.

Here is a quick demonstration jsfiddle: http://jsfiddle.net/H88tS/

Note that the fiddle is linking in the bignumber library.

$(document).ready(function () {

    BigNumber.config({ DECIMAL_PLACES : 50, ERRORS : false});

    var pi = new BigNumber(0, 10),
        x = new BigNumber(1, 10),
        two = new BigNumber(2, 10),
        four = new BigNumber(4, 10);

    function iterate() {
        pi = pi.plus(four.dividedBy(x));
        x = x.plus(two);
        pi = pi.minus(four.dividedBy(x));
        x = x.plus(two);
        $("#pi").text(pi.toPrecision(50));
    }

    $('button').click(iterate);
});
Community
  • 1
  • 1
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
0

Unfortunately, it's computationally impossible to prevent rounding of a number with potentially infinite decimal places.

There are some hacks one could suggest, though, like having a class HugeNumber whose objects are lists or arrays of algarisms, or even strings that contain only numbers, and having arithmetic operations implemented in it (by yourself, of course). Unless processing efficiency is a concern, this would be an acceptable solution. Maybe something like that already exists in a plugin or even in some built-in class, I just never needed that so I really don't know.

lucasnadalutti
  • 5,818
  • 1
  • 28
  • 48