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

后端 未结 14 1314
走了就别回头了
走了就别回头了 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:54

    Since ES2017 padding to a minimum length can be done simply with String.prototype.padStart and String.prototype.padEnd:

    let num = 3
    let str = num.toString().padStart(3, "0")
    console.log(str) // "003"
    

    Or if only the whole part of a float should be a fixed length:

    let num = 3.141
    let arr = num.toString().split(".")
    arr[0] = arr[0].padStart(3, "0")
    let str = arr.join(".")
    console.log(str) // "003.141"
    

提交回复
热议问题