在JavaScript中用前导零填充数字\[重复\]

JavaScript

2020-03-13

在JavaScript中,我需要填充。

例如,如果我有数字9,它将是“ 0009”。如果我有10个数字,则为“ 0010”。请注意,它将始终包含四个数字。

一种方法是减去数字减4以获得我需要输入的0。

是否有一种轻松的方法?

第1517篇《在JavaScript中用前导零填充数字\[重复\]》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
StafanDavaid 2020.03.13

为了娱乐,不要使用循环来创建额外的零:

function zeroPad(n,length){
  var s=n+"",needed=length-s.length;
  if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
  return s;
}
A逆天猿 2020.03.13
function padToFour(number) {
  if (number<=9999) { number = ("000"+number).slice(-4); }
  return number;
}

Something like that?

Bonus incomprehensible-but-slicker single-line ES6 version:

let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;

ES6isms:

  • let is a block scoped variable (as opposed to var’s functional scoping)
  • => is an arrow function that among other things replaces function and is prepended by its parameters
  • If a arrow function takes a single parameter you can omit the parentheses (hence number =>)
  • If an arrow function body has a single line that starts with return you can omit the braces and the return keyword and simply use the expression
  • To get the function body down to a single line I cheated and used a ternary expression
前端LEY米亚 2020.03.13

您可以执行以下操作:

function pad ( num, size ) {
  return ( Math.pow( 10, size ) + ~~num ).toString().substring( 1 );
}

编辑:这只是一个函数的基本思想,但是要增加对较大数字(以及无效输入)的支持,可能会更好:

function pad ( num, size ) {
  if (num.toString().length >= size) return num;
  return ( Math.pow( 10, size ) + Math.floor(num) ).toString().substring( 1 );
}

这有两件事:

  1. 如果该数字大于指定的大小,它将仅返回该数字。
  2. 使用Math.floor(num)代替~~num将支持更大的数字。
神奇启人 2020.03.13

有趣的是,我最近不得不这样做。

function padDigits(number, digits) {
    return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}

使用方式如下:

padDigits(9, 4);  // "0009"
padDigits(10, 4); // "0010"
padDigits(15000, 4); // "15000"

不漂亮,但有效。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android