skip to Main Content

I’m trying to get readable results from this:

const rate = (648735n * 10n**36n) / 124124124n;

I get this result:

rate = 5226502142323276335871663432645856n

But result should be something like this:

5226500000000000000000000000000000n

Is there any way to achieve this? Something like Math.floor 🙂 but for BigInt.

2

Answers


  1. Specifically for formatting output (as strings), you can use Intl.NumberFormat. Example:

    > var nf = new Intl.NumberFormat('en-US', {maximumSignificantDigits: 3});
    > nf.format(12345678n)
    < '12,300,000'
    

    Note how this counts significant digits "from the left".

    If you need more flexibility, you can craft your own mechanism based on division by a power of ten, for example:

    > var divisor = 10n ** 9n;  // a billion
    > var big = 123456789012n;
    > `About ${big / divisor} billions`
    < 'About 123 billons'
    > `Rounded down: ${(big / divisor) * divisor}`
    < 'Rounded down: 123000000000'
    

    Note that this counts zeroes "from the right". If you need to count significant digits from the left, you could first detect the range of the value by comparing it to a series of (precomputed?) powers of ten.

    Login or Signup to reply.
  2. You could do something like:

    const out = rate / 10000 * 10000;
    

    This will 0 out the last 4 digits.

    Generalized:

    function roundDown(input, digits) {
    
      return input / (10n ** digits) * (10n ** digits);
    
    }
    
    roundDown(5226502142323276335871663432645856n, 15n);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search