不足几位数:前面补零

js

function PrefixInteger(num, length) {

  return (Array(length).join('0') + num).slice(-length);
}
 
 
 
function PrefixInteger(num){
 return ('000000000'+num).slice(-10);
}
 
function PrefixInteger(num, length) {
  return (num/Math.pow(10,length)).toFixed(length).substr(2);
}
 
 //闭包
var pad = function() {
 var tbl = [];
 return function(num, n) {
  var len = n-num.toString().length;
  if (len <= 0) return num;
  if (!tbl[len]) tbl[len] = (new Array(len+1)).join('0');
  return tbl[len] + num;
 }
}();

pad(10,4);

//返回:0010


pad(1,4);

//返回:1000

 

 
 
 
 

C#

不足五位数:前面补零

String.Format("{0:D5}",3); //00003

3.ToString("D5");    // 00003

 

 

固定长度一个数值其它方法:

i.ToString().PadLeft(10,'0');
固定长度为10,左不足补0,结果为0000000001;

 

 

 

参考

https://www.cnblogs.com/zhangqs008/archive/2012/02/01/2341078.html
https://www.cnblogs.com/diwu/articles/Csharp_tostring.html

https://docs.microsoft.com/zh-cn/dotnet/standard/base-types/standard-numeric-format-strings

posted @ 2018-11-30 13:53  July_Zheng  阅读(1256)  评论(0编辑  收藏  举报