在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
使用ES6+ JavaScript:
你可以用下面的函数来“零填充一个数字”:
/**
* @param number The number
* @param minLength Minimal length for your string with leading zeroes
* @return Your formatted string
*/
function zerofill(nb, minLength) {
// Convert your number to string.
let nb2Str = nb.toString()
// Guess the number of zeroes you will have to write.
let nbZeroes = Math.max(0, minLength - nb2Str.length)
// Compute your result.
return `${ '0'.repeat(nbZeroes) }${ nb2Str }`
}
console.log(zerofill(5, 6)) // Displays "000005"
ES2017 +:
/**
* @param number The number
* @param minLength Minimal length for your string with leading zeroes
* @return Your formatted string
*/
const zerofill = (nb, minLength) => nb.toString().padStart(minLength, '0')
console.log(zerofill(5, 6)) // Displays "000005"
其他回答
快速而肮脏的方式:
y = (new Array(count + 1 - x.toString().length)).join('0') + x;
当x = 5 count = 6时y = "000005"
最新的方法要简单得多:
var number = 2
number.toLocaleString(undefined, {minimumIntegerDigits:2})
输出:“02”
我只是偶然发现这篇文章寻找一个本地的解决方案。由于没有内置的解决方案,以下是我的看法:
function zerofill(number, width) {
var num = '';
while (width-- > 0) {
num += '0';
}
return num.slice(0, - (number + '').length) + number + '';
}
我对这个话题的一点贡献(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"
我知道,这是一个很脏的函数,但它很快,即使是负数也能工作;)
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'