在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
在JavaScript中推荐的零填充方法是什么?我想我可以构建一个自定义函数来填充零到类型转换的值,但我想知道是否有更直接的方法来做到这一点?
注意:这里的“zeroffilled”指的是数据库意义上的单词(其中数字5的6位零填充表示形式将是“000005”)。
当前回答
我在这个表单中没有看到任何答案所以这里是我的正则表达式和字符串操作
(也适用于负数和小数)
代码:
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'
其他回答
我经常使用这个结构来填充某个值n,已知是一个正的小数:
(offset + n + '').substr(1);
其中偏移量为10^^位。
例如,填充到5位数,其中n = 123:
(1e5 + 123 + '').substr(1); // => 00123
十六进制的版本稍微详细一些:
(0x100000 + 0x123).toString(16).substr(1); // => 00123
注1:我也喜欢@profitehlolz的解决方案,它是这个的字符串版本,使用slice()的漂亮的负索引特性。
我只是偶然发现这篇文章寻找一个本地的解决方案。由于没有内置的解决方案,以下是我的看法:
function zerofill(number, width) {
var num = '';
while (width-- > 0) {
num += '0';
}
return num.slice(0, - (number + '').length) + number + '';
}
function zeroFill(number, width) {
width -= (number.toString().length - /\./.test(number));
if (width > 0) {
return new Array(width + 1).join('0') + number;
}
return number + ""; // always return a string
}
对Peter的代码做了轻微的修改。在他的代码中,如果输入是(1.2,3),返回值应该是01.2,但它返回的是1.2。这里的变化应该会纠正这一点。
我真的不知道为什么,但没有人用最明显的方式去做。这是我的实现。
功能:
/** Pad a number with 0 on the left */
function zeroPad(number, digits) {
var num = number+"";
while(num.length < digits){
num='0'+num;
}
return num;
}
原型:
Number.prototype.zeroPad=function(digits){
var num=this+"";
while(num.length < digits){
num='0'+num;
}
return(num);
};
很简单,我看不出还有什么比这更简单的了。出于某种原因,我在这里已经看到很多次了,人们只是试图不惜一切代价避免“For”和“while”循环。使用regex可能会为这样一个微不足道的8位数填充花费更多的周期。
这是我写的一个angular提供程序,它利用了@profitehlolz的答案,但使用了内存,这样常用的pad长度-pad字符组合就不会不必要地调用数组构建连接:
angular.module('stringUtilities', [])
.service('stringFunctions', [function() {
this.padMemo={ };
this.padLeft=function(inputString,padSize,padCharacter) {
var memoKey=padSize+""+padCharacter;
if(!this.padMemo[memoKey]) {
this.padMemo[memoKey]= new Array(1 + padSize).join(padCharacter);
}
var pad=this.padMemo[memoKey];
return (pad + inputString).slice(-pad.length);
};
}]);