How can I format an integer to a specific length in javascript?

后端 未结 14 1281
走了就别回头了
走了就别回头了 2021-02-03 17:06

I have a number in Javascript, that I know is less than 10000 and also non-negative. I want to display it as a four-digit number, with leading zeroes. Is there anything more e

14条回答
  •  孤街浪徒
    2021-02-03 17:56

    I came looking for the answer, but I think this is a better functional approach (ES6):

    const formatNumberToString = (num, minChars) => {
      return num.toString().length < minChars
       ? formatNumberToString(`0${num}`, minChars)
       : num.toString()
    }
    // formatNumberToString(12, 4) // "0012"
    // formatNumberToString(12, 5) // "00012"
    // formatNumberToString(1, 4) // "0001"
    // formatNumberToString(1, 2) // "01"
    // formatNumberToString(12, 2) // "12"
    // formatNumberToString(12, 1) // "12"
    

    also, this can be implemented just in one line

提交回复
热议问题