How to display more than 20 decimal points in javascript?

╄→尐↘猪︶ㄣ 提交于 2019-12-06 16:22:23

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.

I'll cheat:

var pi = '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912983367336244065664308602139494639522473719070217986094370277053921717629317675238467481846766940513200056812714526356082778577134275778960917363717872146844090122495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134999999837297804995105973173281609631859502445945534690830264252230825334468503526193118817101000313783875288658753320838142061717766914730359825349042875546873115956286388235378759375195778185778053217122680661300192787661119590921642019';

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));
}

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"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!