微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript如何将整数四舍五入并找到它的加值?

如何解决Javascript如何将整数四舍五入并找到它的加值?

目标

我正处于编写 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,4,8,3,5,8]));

以上代码总结

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

问题

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

解决方法

你可以这样做:

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://stackoverflow.com/users/13762301/pilchard

,

认为你需要的是这个:

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

然后使用此检查差异:

Math.abs(newNum - oldNum);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。