Krishna Kamal
Krishna Kamal

Reputation: 771

How to get Power of big number in decimal?

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.

Upvotes: 3

Views: 4843

Answers (3)

Lee
Lee

Reputation: 418

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

Upvotes: -3

T.J. Crowder
T.J. Crowder

Reputation: 1074218

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.

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386560

You could use BigInt, if implemented.

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

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

Upvotes: 5

Related Questions