在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
一个简单的递归函数来实现您的建议:
function padleft (YourNumber, OutputLength){
if (YourNumber.length >= OutputLength) {
return YourNumber;
} else {
return padleft("0" +YourNumber, OutputLength);
}
}
YourNumber是输入的数字。 OutputLength是首选的输出数字长度(剩余填充为0)。
如果您的输入数字长度小于所需的输出数字长度,此函数将在左侧添加0。
其他回答
我在这里寻找一个标准,和保罗和约拿单有同样的想法……他们的照片超级可爱,但这里有一个非常可爱的版本:
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'
可变长度填充功能:
function addPaddingZeroes(value, nLength)
{
var sValue = value + ''; // Converts to string
if(sValue.length >= nLength)
return sValue;
else
{
for(var nZero = 0; nZero < nLength; nZero++)
sValue = "0" + sValue;
return (sValue).substring(nLength - sValue.length, nLength);
}
}
我对这个话题的一点贡献(https://gist.github.com/lucasferreira/a881606894dde5568029):
/* Autor: Lucas Ferreira - http://blog.lucasferreira.com | Usage: fz(9) or fz(100, 7) */
function fz(o, s) {
for(var s=Math.max((+s||2),(n=""+Math.abs(o)).length); n.length<s; (n="0"+n));
return (+o < 0 ? "-" : "") + n;
};
用法:
fz(9) & fz(9, 2) == "09"
fz(-3, 2) == "-03"
fz(101, 7) == "0000101"
我知道,这是一个很脏的函数,但它很快,即使是负数也能工作;)
我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作
(也适用于负数和小数)
代码:
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 zeroPad(num,digits){ return ((num/Math.pow(10,digits))+'').slice(2) }