在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
我使用这个片段来获得一个五位数的表示:
(value+100000).toString().slice(-5) // "00123" with value=123
其他回答
我只是偶然发现这篇文章寻找一个本地的解决方案。由于没有内置的解决方案,以下是我的看法:
function zerofill(number, width) {
var num = '';
while (width-- > 0) {
num += '0';
}
return num.slice(0, - (number + '').length) + number + '';
}
ES6让这一点变得相当微不足道:
function pad (num, length, countSign = true) {
num = num.toString()
let negative = num.startsWith('-')
let numLength = negative && !countSign ? num.length - 1 : num.length
if (numLength >= length) {
return num
} else if (negative) {
return '-' + '0'.repeat(length - numLength) + num.substr(1)
} else {
return '0'.repeat(length - numLength) + num
}
}
pad(42, 4) === '0042'
pad(12345, 4) === '12345'
pad(-123, 4) === '-100'
pad(-123, 4, false) === '-0100'
ECMAScript 2017: 使用padStart或padEnd
'abc'.padStart(10); // " abc"
'abc'.padStart(10, "foo"); // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
更多信息:
https://github.com/tc39/proposal-string-pad-start-end https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
我在写一个数字基础转换器时,想到了一个荒谬的单行程序。
//这是被诅咒的 函数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个字符长),这是很方便的。
我不知道它的性能有多好,但是,嘿,至少它已经被缩小了!
我觉得我的方法有点不同。我需要填充一个数字的原因是在<pre>元素(屏幕日志的一部分)中显示它,所以它最终将是一个字符串。我没有做任何数学运算,而是写了一个简单的函数来覆盖一个掩码字符串上的字符串值:
function overlayr(m, s) {
return m.length > s.length ? m.substr(0, m.length - s.length) + s : s;
}
这样做的好处是,我可以将它用于各种字符串对齐任务。要调用它,只需传入掩码和数字作为字符串:
> overlayr('00000', (5).toString())
< "00005"
作为一个额外的好处,它可以正确地处理溢出:
> overlayr('00000', (555555).toString())
< "555555"
当然它不局限于0填充:
> overlayr('*****', (55).toString())
< "***55"