admin管理员组

文章数量:1410717

How to get big power of 2 in decimal or how to convert big exponential value into decimal value.

I want 2 to the power of 128 in decimal not exponential what I did till now

tofixed(+exponent) 

which again given me the same value.

 var num =  Math.pow(2, 128);

Actual result = 3.402823669209385e+38 expected some decimal value not exponential value.

How to get big power of 2 in decimal or how to convert big exponential value into decimal value.

I want 2 to the power of 128 in decimal not exponential what I did till now

tofixed(+exponent) 

which again given me the same value.

 var num =  Math.pow(2, 128);

Actual result = 3.402823669209385e+38 expected some decimal value not exponential value.

Share Improve this question asked Jun 24, 2019 at 8:13 Krishna KamalKrishna Kamal 7712 gold badges10 silver badges23 bronze badges 5
  • Do you mean scientific notation? – Jack Bashford Commented Jun 24, 2019 at 8:15
  • @JackBashford or standard form here in the UK :p – Kobe Commented Jun 24, 2019 at 8:16
  • yeah you can say that. – Krishna Kamal Commented Jun 24, 2019 at 8:16
  • JS doesn't support that natively - and what rounding would you like? – Jack Bashford Commented Jun 24, 2019 at 8:16
  • power of 2 would be an integer right. So where round came into picture – Krishna Kamal Commented Jun 24, 2019 at 8:18
Add a ment  | 

3 Answers 3

Reset to default 5

You could use BigInt, if implemented.

var num =  BigInt(2) ** BigInt(128);

console.log(num.toString());
console.log(BigInt(2 ** 128).toString());

3.402823669209385e+38 is a decimal number (in string form, because it's been output as a string). It's in scientific notation, specifically E-notation. It's the number 3.402823669209385 times 100000000000000000000000000000000000000.

If you want a string that isn't in scientific notation, you can use Intl.NumberFormat for that:

console.log(new Intl.NumberFormat().format(Math.pow(2, 128)));

Note: Although that number is well outside the range that JavaScript's number type can represent with precision in general (any integer above Number.MAX_SAFE_INTEGER [9,007,199,254,740,991] may be the result of rounding), it's one of the values that is held precisely, even at that magnitude, because it's a power of 2. But operations on it that would have a true mathematical result that wasn't a power of 2 would almost certainly get rounded.

I think the default power function won't be able to the results you want. You can refer to the article below to understand how to create an Power function with big number by yourself.

Demo code is not JS but still quite understandable.

Writing power function for large numbers

本文标签: javascriptHow to get Power of big number in decimalStack Overflow