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

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

Trailing zero 尾隨零 – JS 數字後面補0

Trailing zero 尾隨零,是與 Leading zero 前導零 完全相反的概念,是在數字後面補0,詳細可以看維基百科的解說,具體用法如下

直觀的對比就如下:

一般數字經過 Trailing zero 處理
123123000000
44444444440000
5566666556666600
7890789000000
9876543987654300
一般數字 與 經過 Trailing zero 處理,後面補0後的比較

JS 數字後面補0

Trailing zero的概念是沒有滿足長度時,往後面補0,可以直接照下面這樣做。

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

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

// output : 'abc1230000'

同樣,你可以在後面加上任何你想加的符號,直接把 join()中的0,改成你希望補的代號就可以了。

相容 IE 老系統

如果你是串接很老的系統,比方說對方還是使用 IE 開啟,可以更換為以下代碼:

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

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

// output : 'abc1230000'

5 留言

  1. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.com/sl/register-person?ref=DB40ITMB

  2. Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

  3. Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

  4. Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

發表迴響