Format a Number, Exactly Two in Length?

前端 未结 10 647
既然无缘
既然无缘 2021-02-03 21:49

I have an integer that is less then 100 and is printed to an HTML page with JavaScript. How do I format the integer so that it is exactly two digits long? For example:

相关标签:
10条回答
  • 2021-02-03 22:21
    // Return a string padded
    function FormatMe(n) {
       return (n<10) ? '0'+n : n;
    }
    
    0 讨论(0)
  • 2021-02-03 22:23

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

    String(number).padStart(2, '0')
    
    0 讨论(0)
  • 2021-02-03 22:25

    I usually use this function.

    function pad(n, len) {
        let l = Math.floor(len)
        let sn = '' + n
        let snl = sn.length
        if(snl >= l) return sn
        return '0'.repeat(l - snl) + sn
    }
    


    Usage Example

    pad(1, 1)    // ==> returns '1' (string type)
    pad(384, 5)  // ==> returns '00384'
    pad(384, 4.5)// ==> returns '0384'
    pad(5555, 2) // ==> returns '5555'
    
    0 讨论(0)
  • 2021-02-03 22:27

    I use regex to format my time such as

    const str = '12:5'

    const final = str.replace(/\d+/g, (match, offset, string) => match < 10 ? '0' + match : match)

    output: 12:05

    0 讨论(0)
提交回复
热议问题