javascriptbigintceil

JavaScript BigInt ceil() function


Given that Math.ceil(1/3) yields 1, how do I get that 1 (or 1n) from BigInt input values of 1n and 3n? Obviously Math.ceil(Number(1n)/Number(3n)) would work but some bigints might be too big for that approach.


Solution

  • Create a simple function

    Note: the .toString() is ONLY so the console output is shown here

    const ceilN = (n, d) => n / d + (n % d ? 1n : 0n)
    
    console.log(ceilN(120n, 3n).toString()); // 40
    console.log(ceilN(121n, 3n).toString()); // 41
    console.log(ceilN(122n, 3n).toString()); // 41
    console.log(ceilN(123n, 3n).toString()); // 41