在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
快速而肮脏的方式:
y = (new Array(count + 1 - x.toString().length)).join('0') + x;
当x = 5 count = 6时y = "000005"
其他回答
这一种不太本土,但可能是最快的…
zeroPad = function (num, count) {
var pad = (num + '').length - count;
while(--pad > -1) {
num = '0' + num;
}
return num;
};
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'
这个方法不是更快,但它相当原生。
zeroPad = function (num, count) {
return [Math.pow(10, count - num.toString().length), num].join('').substr(1);
};
function zeroPad(num,digits){ return ((num/Math.pow(10,digits))+'').slice(2) }
第一个参数是任何实数,第二个参数是一个正整数,指定小数点左边的最小位数,第三个参数是一个可选的正整数,指定小数点右边的数字。
function zPad(n, l, r){
return(a=String(n).match(/(^-?)(\d*)\.?(\d*)/))?a[1]+(Array(l).join(0)+a[2]).slice(-Math.max(l,a[2].length))+('undefined'!==typeof r?(0<r?'.':'')+(a[3]+Array(r+1).join(0)).slice(0,r):a[3]?'.'+a[3]:''):0
}
so
zPad(6, 2) === '06'
zPad(-6, 2) === '-06'
zPad(600.2, 2) === '600.2'
zPad(-600, 2) === '-600'
zPad(6.2, 3) === '006.2'
zPad(-6.2, 3) === '-006.2'
zPad(6.2, 3, 0) === '006'
zPad(6, 2, 3) === '06.000'
zPad(600.2, 2, 3) === '600.200'
zPad(-600.1499, 2, 3) === '-600.149'