0

I am trying to do this:

const numerator = 268435456;
const denominator = 2 ** 64;
const decimalFraction = numerator / denominator;

To make this work, I have tried to use the code suggested here: https://stackoverflow.com/a/54409977/3846032:

const rawValue = 268435456n;
const exponent = 2n ** 64n;
const precision = 100_000_000;
const fraction = Number((rawValue * BigInt(precision)) / exponent) / precision;

When I run this in dev it works fine, but in prod I get this error:

Uncaught TypeError: can't convert BigInt to number

I believe it is coming from 2n ** 64n.

I'm using create-react-app and some digging reveals this: https://github.com/facebook/create-react-app/issues/6907#issuecomment-778178677).

Unfortunately this suggestion makes it fail in both dev and prod with an OOM error.

Any suggestions on how to make this work would be appreciated.

Daniel Porteous
  • 5,536
  • 3
  • 25
  • 44
  • 1
    Why are you still using normal numbers with BigInt? `precision` should use BigInt as well: `100_000_000n`, so then you'd just use `(rawValue * precision) / exponent / precision`. – kelsny Jan 09 '23 at 16:39
  • Because I want to get a decimal `number` at the end of this. Regardless, if I try what you suggest, unfortunately I still get the same problem with the OOM. – Daniel Porteous Jan 09 '23 at 16:41
  • `268435456 / Math.pow(2, 64)` gives me the expected `1.4551915228366852e-11` in my react-app – 0stone0 Jan 09 '23 at 16:45
  • Ahhh, the OOM was a problem later in the code, my bad. Let me write an answer summarizing what to do. – Daniel Porteous Jan 09 '23 at 16:56
  • You'll need more than `100_000_000` for the precision because the quotient of your example is on the order of 1e-11. In other words, even if your example worked, it would display 0. e.g.: `Number((268435456n * 100_000_000n) / 2n ** 64n) / 100_000_000` is `0`. but `Number((268435456n * 100_000_000_000n) / 2n ** 64n) / 100_000_000_000` is `1e-11` – Wyck Jan 09 '23 at 17:40

2 Answers2

0

Use Math.pow(2, 64) instead of 2 ** 64:

const Example = () => {

    const x = 268435456;
    const y = Math.pow(2, 64);

    return (x / y);
}

ReactDOM.render(<Example />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
0stone0
  • 34,288
  • 4
  • 39
  • 64
0

So it turns out the OOM I was getting was unrelated to this particular problem, so disregard that part.

As for this error:

Uncaught TypeError: can't convert BigInt to number

You can avoid it by doing Math.power(2, 64) instead of 2n ** 64n.

The issue in question: https://github.com/facebook/create-react-app/issues/11705.

Daniel Porteous
  • 5,536
  • 3
  • 25
  • 44