Monday, December 4, 2023
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  124] [ 3]  / answers: 1 / hits: 132789  / 15 Years ago, tue, july 14, 2009, 12:00:00

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.


More From » formatting

 Answers
78

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.


[#99128] Thursday, July 9, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
quinlanhenryf

Total Points: 743
Total Questions: 93
Total Answers: 118

Location: Australia
Member since Sat, May 27, 2023
7 Months ago
;