用零截断并舍入 BigInt

Truncate with zeros and round BigInt

我有一个 BigInt 123456789n。我想用两个零将其截断为 123456700n。但我认为这还不够好——我希望最后一个剩余数字被最后一个截断的数字四舍五入。所以结果应该是123456800n.

示例:

1100n should be 1100n
1149n should be 1100n
1150n should be 1200n
1199n should be 1200n

具有可配置数量的零的解决方案将是惊人的。

我有一个涉及太多字符串的解决方案。欢迎不那么丑的东西。

function truncateAndRound(input) {
  let str = input.toString();
  if (str.length < 2) {
    str = str.padStart(2, '0');
  }

  let num = BigInt(str) / 100n;
  const fraction = BigInt(str.slice(str.length - 2, str.length));

  if (fraction >= 50n) {
    num += 1n;
  }
  str = num.toString();

  return str + '00';
}

console.log(truncateAndRound(1100n));
console.log(truncateAndRound(1149n));
console.log(truncateAndRound(1150n));
console.log(truncateAndRound(1199n));

也许这样的方法行得通?

const f = (x,y) => ((x / y) * y) + (x%y >= 5n*(y/10n) ? y : 0n);
const y = 100n; // amount of padding, 100 = 2 last digits will become 0, 1000 = 3 last, etc. 
console.log(f(1100n, y)); // 1100n
console.log(f(1149n, y)); // 1100n
console.log(f(1150n, y)); // 1200n
console.log(f(1199n, y)); // 1200n
console.log(f(1200n, y)); // 1200n
console.log(f(11499n, 1000n)); // 11000n
console.log(f(11500n, 1000n)); // 12000n
console.log(f(123456789n, y)); // 123456800n
<!-- See browser console for output -->

y = 100 时,(x / y) * y 将从数字 x 中删除最后两位数字。 例如:

(x/y) = 1149n / 100n = 11n 
(x/y) * y = 11n * 100n = 1100n 

现在只需决定是将 y 添加到上述结果(即:向上舍入)还是保持原样(向下舍入)。可能有一种更数学的方法可以做到这一点,但一种方法可能是使用三元。

比如1149,我们要变成0的最后一位是49,这个可以查看是否大于等于50,如果是就是,加y。小于50则加0。