简体   繁体   中英

How to display more than 20 decimal points in javascript?

I am making a webpage that displays the digits of pi. I was able to get my pi variable to display 20 digits of pi using the toFixed method but I am wondering if I can display more. Is the number of decimal places limited by the memory size of my variable? Is there a way to display more than 20 digits?

EDIT: I should have clarified that I was using the Chudnovsky Algorithmn to calculate the value of pi. I assuming that because of the memory limitations of the var variable that it can only display up to a certain amount of digits which is limited to 20? Source

You can't.

Try storing the bits in more than one variable, use a string, or get a bignum library , or if you only need to deal with integers, a biginteger library.

You can't do this with native JavaScript for more info see this .

The following is cast to float:

var x =  3.14159265358979323846;
print(x.toFixed(20));

However , you can either print a string or to use mathjs :

var one = math.bignumber(1);
var pi = math.bignumber('3.14159265358979323846');
var ans = math.multiply(one, pi);
print(ans.toString());

Will give you "3.14159265358979323846"

I'll cheat:

 var pi = '3.'; var piDecimal = function(numDigits) { return pi.substr(0, numDigits + 2); // Add 2 to compensate for "3." }; for (var i = 1; i < 100; i++) { console.log(i + ' decimal place' + (i === 1 ? '' : 's') + ': ' + piDecimal(i)); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM