在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
这是你能找到的最简单、最直接的解决方案。
function zerofill(number,length) {
var output = number.toString();
while(output.length < length) {
output = '0' + output;
}
return output;
}
其他回答
还有另一个版本:
function zPad(s,n){
return (new Array(n+1).join('0')+s).substr(-Math.max(n,s.toString().length));
}
这里有一个两行函数中的数组解。它还检查前导零是否小于数字字符串的长度。
function pad(num, z) {
if (z < (num = num + '').length) return num;
return Array(++z - num.length).join('0') + num;
}
我们的测试是假的,因为我的有个错别字。
zeroPad = function (num, count) {
return ((num / Math.pow(10, count)) + '').substr(2);
};
Paul的是最快的,但我认为.substr比.slice快,即使它多了一个字符;)
这是我想出的一个快速函数。如果有人有更简单的方法,欢迎分享!
function zerofill(number, length) {
// Setup
var result = number.toString();
var pad = length - result.length;
while(pad > 0) {
result = '0' + result;
pad--;
}
return result;
}
我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作
(也适用于负数和小数)
代码:
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'