在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
这就是ES6的解决方案。
函数pad(num, len) { 返回“0”。repeat(len - num. tostring ().length) + num; } 警报(垫(1234 6));
其他回答
function uint_zerofill(num, width) {
var pad = ''; num += '';
for (var i = num.length; i < width; i++)
pad += '0';
return pad + num;
}
我使用
Utilities.formatString("%04d", iThe_TWO_to_FOUR_DIGIT)
哪个前导有4个0
注:这需要谷歌的应用程序脚本实用程序:
https://developers.google.com/apps-script/reference/utilities/utilities#formatstringtemplate-args
我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作
(也适用于负数和小数)
代码:
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'
也许我太天真了,但我认为这在一行简单而有效的代码中就可以实现(对于正数):
padded = (value + Math.pow(10, total_length) + "").slice(1)
只要你保持你的长度根据你的值集(在任何零填充),这应该是可行的。
步骤如下:
10的幂与正确的0数相加[69+1000 = 1069] 转换为字符串+"" [1069 => "1069"] 对第一个1进行切片,这是第一个乘法的结果["1069" => "069"]
对于自然列表(文件,dirs…)是非常有用的。
一个简单的递归函数来实现您的建议:
function padleft (YourNumber, OutputLength){
if (YourNumber.length >= OutputLength) {
return YourNumber;
} else {
return padleft("0" +YourNumber, OutputLength);
}
}
YourNumber是输入的数字。 OutputLength是首选的输出数字长度(剩余填充为0)。
如果您的输入数字长度小于所需的输出数字长度,此函数将在左侧添加0。