紀錄工作經驗、相關知識,解決技術相關問題。

Javascript, 未分類, 網站相關, 資訊相關

Leading zero 前導零 – JS 數字前補0

Leading zero 前導零,也就是常在數字前面看到的一串補0,有興趣可以看維基百科的詳細解釋。

直觀的對比就如下:

一般數字經過 Leading Zero 處理
123000000123
44444000044444
5566666005566666
7890000007890
9876543009876543
一般數字 與 經過 Leading Zero 處理,前面補0後的比較

JS 數字前面補0

程式在處理資料時,很多時候都會用到Leading zero的概念,尤其一串編號要進行格式統整時,這時可以直接照下面這樣做。

// 數字、字串前補0
// code : 你輸入的資料(字串、數字)
// dataLength : 資料補0後的長度
function LeadingZero( code, dataLength){
  var str = Array(10).join('0') + code;
  return str.slice(0 - dataLength)
}

var str = 'abc123'
console.log(LeadingZero(str , 10))

// output : '0000abc123'

如果你希望前面補的不是數字0 ,而是其他自訂的代號,可以直接把 join()中的0改成你要補的代號就好。

相容 IE 老系統

如果你用的系統很老,還在使用 IE 開啟,較早期的版本是沒有支援Join的,所以可以改寫成以下代碼:

// input: (123 , 8) , output : 00000123
function LeadingZero( code, dataLength){
  var str = '0000000000' + code;
  return str.slice(0 - dataLength);
}

var str = 'abc123'
console.log(LeadingZero(str , 10))

// output : '0000abc123'

10 留言

  1. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  2. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  3. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  4. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  5. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  6. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  7. Reading your article has greatly helped me, and I agree with you. But I still have some questions. Can you help me? I will pay attention to your answer. thank you.

  8. Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!

發表迴響