How can I format an integer to a specific length in javascript?
formatting, javascript
Solution
Since ES2017 padding to a minimum length can be done simply with String.prototype.padStart and String.prototype.padEnd:
let number = 3
let string = number.toString().padStart(3, '0')
console.log(string) // "003"
Or if only the whole part of a float should be a fixed length:
let number = 3.141
let array = number.toString().split('.')
array[0] = array[0].padStart(3, '0')
let string = array.join('.')
console.log(string) // "003.141"
Neither of these simple uses handle sign, only showing a fraction part when number is not an integer, or other scenarios - so here is a simple example formatting function without options:
function format (number) {
let [ integer, fraction = '' ] = number.toString().split('.')
let sign = ''
if (integer.startsWith('-')) {
integer = integer.slice(1)
sign = '-'
}
integer = integer.padStart(3, '0')
if (fraction) {
fraction = '.' + fraction.padEnd(6, '0')
}
let string = sign + integer + fraction
return string
}
console.log(format(3)) // "003"
console.log(format(-3)) // "-003"
console.log(format(4096)) // "4096"
console.log(format(-3.141)) // "-003.141000"
Although notably this will not handle things that are not numbers, or numbers that toString into scientific notation.
Problem
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 elegant than the following? ``` if(num<10) num="000"+num; else if(num<100) num="00"+num; else if(num<1000) num="0"+num; ``` I want something that is built into Javascript, but I can't seem to find anything.