在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
一个愚蠢的递归方法是:
function paddingZeros(text, limit) {
if (text.length < limit) {
return paddingZeros("0" + text, limit);
} else {
return text;
}
}
这里的限制是你想要的字符串大小。
例如: appendZeros(“7829”, 20) // 00000000000000007829
其他回答
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零领先”参考考虑 浏览量和回答量都很高。
只是另一种解决方案,但我觉得更容易辨认。
函数zeroFill(text, size) { 而(文本。长度< size){ Text = "0" + Text; } 返回文本; }
一个愚蠢的递归方法是:
function paddingZeros(text, limit) {
if (text.length < limit) {
return paddingZeros("0" + text, limit);
} else {
return text;
}
}
这里的限制是你想要的字符串大小。
例如: appendZeros(“7829”, 20) // 00000000000000007829
我在写一个数字基础转换器时,想到了一个荒谬的单行程序。
//这是被诅咒的 函数p (i, w、z) {z z = | | 0; w = w | | 8; i + = "; var o w = i.length %;还啊?[…数组(言).fill (z),……我]. join():我;} console.log (p (8675309));//默认:pad w/ 0到8位 console.log (p(525600年,10));//输入10个数字 console.log(p(69420, 10, 'X'));// Pad w/ X到10位 console.log (p (8675309, 4));//输入4位数字 console.log (p (12345678));//没必要就别拍
或者,以一种不那么容易暴露我把灵魂出卖给黑Perl的形式:
function pad(input, width, zero) {
zero = zero || 0; width = width || 8; // Defaults
input += ''; // Convert input to string first
var overflow = input.length % width // Do we overflow?
if (overflow) { // Yep! Let's pad it...
var needed = width - overflow; // ...to the next boundary...
var zeroes = Array(needed); // ...with an array...
zeroes = zeroes.fill(zero); // ...full of our zero character...
var output = [...zeroes,...input]; // ...and concat those zeroes to input...
output = output.join(''); // ...and finally stringify.
} else {
var output = input; // We don't overflow; no action needed :)
}
return output; // Done!
}
这个答案与其他答案不同的一点是,它取数字长度对目标宽度的模,而不是简单的大于检查。如果你想确保结果长度是目标宽度的倍数(例如,你需要输出5或10个字符长),这是很方便的。
我不知道它的性能有多好,但是,嘿,至少它已经被缩小了!
最新的方法要简单得多:
var number = 2
number.toLocaleString(undefined, {minimumIntegerDigits:2})
输出:“02”