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

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


当前回答

我没有看到任何人指出,当你使用String.prototype.substr()与负数时,它从右边计数。

OP问题的一个线性解决方案,即数字5的6位零表示,是:

console.log((“00000000” + 5).substr(-6));

概括起来,我们会得到:

函数pad(num, len) {return ("00000000" + num).substr(-len)}; console.log(垫(5、6)); console.log(垫(45岁,6)); console.log (pad (345 6)); console.log (pad (2345 6)); console.log (pad (12345 6));

其他回答

js是一个完整的开源JavaScript sprintf实现 对于浏览器和node.js。 它的原型很简单: 字符串sprintf(字符串格式,[mixed arg1 [, mixed arg2[,…]]])

我想推荐Alexandru meurratisteanu的sprintf模块,整个解决方案看起来就像这样:

var sprintf = require('sprintf');
var zeroFilled = sprintf('%06d', 5);

console.log(zeroFilled); // 000005

注:我是在6年后回答这个问题,但似乎这个 问题成为“javascript零领先”参考考虑 浏览量和回答量都很高。

exports.pad = (num, length) => "0".repeat(length - num.toString().length) + num;

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

(也适用于负数和小数)

代码:

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'

这里有一个我认为很酷的小技巧:

(2/10000).toString().split(".")[1]
"0002"
(52/10000).toString().split(".")[1]
"0052"

我在这里寻找一个标准,和保罗和约拿单有同样的想法……他们的照片超级可爱,但这里有一个非常可爱的版本:

function zeroPad(n, l, i) {
    return (i = n/Math.pow(10, l))*i > 1 ? '' + n : i.toFixed(l).replace('0.', '');
}

这也可以(我们假设是整数,对吗?)…

> zeroPad(Math.pow(2, 53), 20);
'00009007199254740992'

> zeroPad(-Math.pow(2, 53), 20);
'-00009007199254740992'

> zeroPad(Math.pow(2, 53), 10);
'9007199254740992'

> zeroPad(-Math.pow(2, 53), 10);
'-9007199254740992'