0

I'm doing the practice of showing a large number with factorial. The problem is It always round automatically when the result is too large. Here is an example:

function extraLongFactorials(n) {
    const rs = [...Array(n)].reduce((a, b, i) => a*(i+1), 1);
    console.log(rs);
}

extraLongFactorials(25);

The result of the above code is:

1.5511210043330986e+25

When the expected output is

15511210043330985984000000

I try with toFixed() and toLocaleString('fullwide', {useGrouping: false}) but both gave the wrong output.

15511210043330986000000000

Does anybody know how to handle this situation?

3 Answers 3

3

This should work in all browsers that currently support BigInt. Note that operations between BigInt and Number do not mix, so we have to start with BigInt in the first place (notice the n sigil at 1n). rs.toString() is required by StackSnippet because it fakes the console, and the fake console still doesn't know how to print several newer data types from ES6+; real console will know how to print a BigInt normally.

function extraLongFactorials(n) {
    const rs = [...Array(n)].reduce((a, b, i) => a*(BigInt(i+1)), 1n)
    console.log(rs.toString())
}

extraLongFactorials(25)

If your browser doesn't support BigInt, then... then... get a better browser (or use a library like this, I suppose. But get a better browser.)

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a BigInt:

function extraLongFactorials(n) {
  const rs = [...Array(n)].reduce((a, b, i) => a * Bigint(i + 1), 1 n);
  console.log("" + rs)
}

extraLongFactorials(25);

Note that this code does not work on all browsers since it's in Stage 3 of development. It may be added to ECMAScript 9 later this year, making it a full feature (although not all browsers will support it).

3 Comments

Note that this doesn't work for several reasons: the biggest one is that you convert to BigInt too late, so the result has already lost precision. The second is your complaint that it doesn't work on Stack Snippets - Stack Snippets just don't know how to display it, so you need to convert them to string yourself. I posted a corrected version in my answer.
Oh yes @Amadan, sorry about that.
My bad @Amadan - it was my browser that didn't support it.
0

Use BigInt if the expected interger is more than Number.MAX_SAFE_INTEGER

Have a look on Snippet if looking for something without BigInt and any support restriction.

function extraLongFactorials(n) {
	const rs = [...Array(n)].reduce((a, b, i) => a*(i+1), 1)
	console.log('output-'+BigInt(rs))
}
console.log(Number.MAX_SAFE_INTEGER)
extraLongFactorials(25)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.