在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?

注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。


当前回答

我使用这个片段来获得一个五位数的表示:

(value+100000).toString().slice(-5) // "00123" with value=123

其他回答

以下提供了一个快速的解决方案:

函数numberPadLeft(num, max, padder = "0"){ 返回"" == (num += "") ?“”: (dif = Max - num.length, dif > 0 ? 微调电容器。重复(dif < 0 ?0: dif) + num: num) }

一个简单优雅的解,n是数字,l是长度。

函数nFill (n, l){返回(l > n.toString () . length) ?((数组(l) . join(“0”)+ n) .slice (- l)): n;}

这将保持长度,如果它是超过所需的,而不是改变数字。

N = 500; console.log (nFill (n, 5)); console.log (nFill (n, 2)); 函数nFill (n, l){返回(l > n.toString () . length) ?((数组(l) . join(“0”)+ n) .slice (- l)): n;}

我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作

(也适用于负数和小数)

代码:

function fillZeroes(n = 0, m = 1) {
  const p = Math.max(1, m);
  return String(n).replace(/\d+/, x => '0'.repeat(Math.max(p - x.length, 0)) + x);
}

输出:

console.log(fillZeroes(6, 2))          // >> '06'
console.log(fillZeroes(1.35, 2))       // >> '01.35'
console.log(fillZeroes(-16, 3))        // >> '-016'
console.log(fillZeroes(-1.456, 3))     // >> '-001.456'
console.log(fillZeroes(-456.53453, 6)) // >> '-000456.53453'
console.log(fillZeroes('Agent 7', 3))  // >> 'Agent 007'

这是你能找到的最简单、最直接的解决方案。

function zerofill(number,length) {
    var output = number.toString();
    while(output.length < length) {
      output = '0' + output;
    }
    return output;
}

post,如果这是你正在寻找的,将剩余的时间以毫秒为单位转换为字符串,如00:04:21

function showTimeRemaining(remain){
  minute = 60 * 1000;
  hour = 60 * minute;
  //
  hrs = Math.floor(remain / hour);
  remain -= hrs * hour;
  mins = Math.floor(remain / minute);
  remain -= mins * minute;
  secs = Math.floor(remain / 1000);
  timeRemaining = hrs.toString().padStart(2, '0') + ":" + mins.toString().padStart(2, '0') + ":" + secs.toString().padStart(2, '0');
  return timeRemaining;
}