Javascript - How to squared a number?

情到浓时终转凉″ 提交于 2019-12-23 12:54:08

问题


Using the javascript function

function squareIt(number) {
   return number * number;
}

When given the number 4294967296 the function returns 18446744073709552000 is returned

Everyone knows the real answer is 18446744073709551616 :-)

I guess this is to to with rounding on my 32-bit machine. However, would this script give the right answer on a 64 bit machine? Has anyone tried this?


回答1:


ChrisV- see this post. Also it easier for people to evaluate your question by typing the following JavaScript directly into the browser URL textbox:

javascript:4294967296*4294967296



回答2:


Javascript uses 64 bit floating point arithmetic internally for numerical calculations - the results you see are a reflection of this, and will happene regardless of the underlying architecture.




回答3:


what about this

function squareIt(number){
return Math.pow(number,2)
}



回答4:


Here is one more example based on BigInteger.js.

alert(bigInt(4294967296).square());
<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.40/BigInteger.min.js"></script>


来源:https://stackoverflow.com/questions/882080/javascript-how-to-squared-a-number

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