Javascript 如何将整数四舍五入并求其相加值?

Javascript how to round a whole number up and find its addition value?

目标

我正处于编写 Luhn 算法脚本的最后阶段。

问题

假设我有一个最终计算 73

如何舍入到下一个 0?所以最后的值为80.

最后,我怎样才能得到添加的值?例如7是最终答案。

当前代码

function validateCred(array) {
  // Array to return the result of the algorithm
  const algorithmValue = [];

  // Create a [2, 1, 2] Pattern
  const pattern = array.map((x, y) => {
    return 2 - (y % 2);
  });

  // From given array, multiply each element by it's pattern
  const multiplyByPattern = array.map((n, i) => {
    return n * pattern[i];
  });

  // From the new array, split the numbers with length of 2 e.g. 12 and add them together e.g. 1 + 2 = 3
  multiplyByPattern.forEach(el => {
    // Check for lenght of 2
    if(el.toString().length == 2) {
      // Split the number
      const splitNum = el.toString().split('');
      
      // Add the 2 numbers together
      const addSplitNum = splitNum.map(Number).reduce(add, 0);

      // Function to add number together
      function add(accumalator, a) {
        return accumalator + a;
      }
      algorithmValue.push(addSplitNum);
    }

    // Check for lenght of 1
    else if(el.toString().length == 1){
      algorithmValue.push(el);
    }
  });

  // Sum up the algorithmValue together 
  const additionOfAlgorithmValue = algorithmValue.reduce((a, b) => {
    return a + b;
  });

  // Mod the final value by 10
  if((additionOfAlgorithmValue % 10) == 0) {
    return true;
  }
  else{
    return false;
  }
}

// Output is False
console.log(validateCred([2,7,6,9,1,4,8,3,0,4,0,5,9,9,8]));

以上代码总结

输出应该是True。这是因为,我在数组中给出了15位数字的总长度。而它应该是16。我知道第16个值是7,因为给定的数组的总值为73,将它四舍五入到下一个0是80,意味着校验位是7.

问题

如果给定的数组长度小于 15,如何获取支票号码?

认为你需要的是这个:

var oldNum = 73
var newNum = Math.ceil((oldNum+1) / 10) * 10;;

然后用这个检查差异:

Math.abs(newNum - oldNum);

你可以这样做:

let x = [73,81,92,101,423];

let y = x.map((v) => {
let remainder = v % 10;
let nextRounded = v + (10-remainder);
/* or you could use 
let nextRounded = (parseInt(v/10)+1)*10; 
*/
let amountToNextRounded = 10 - remainder;
return [nextRounded,amountToNextRounded];
});

console.log(y);

编辑

正如 @pilchard 所注意到的,您可以使用这种更简化的方式找到 nextRounded

let nextRounded = v + (10-remainder);

https://whosebug.com/users/13762301/pilchard