admin管理员组

文章数量:1134247

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.

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.

Share Improve this question edited Apr 25, 2015 at 15:47 Kip asked Jul 14, 2009 at 20:42 KipKip 109k87 gold badges238 silver badges268 bronze badges
Add a comment  | 

16 Answers 16

Reset to default 129

The simplest way I can think of is this:

("000" + num).slice(-4)

A padded number is a string.
When you add a number to a string, it is converted to a string.
Strings has the method slice, that retuns a fixed length piece of the string.
If length is negative the returned string is sliced from the end of the string.

to test:

var num=12;
console.log(("000" + num).slice(-4)); // Will show "0012"

Of cause this only works for positive integers of up to 4 digits. A slightly more complex solution, will handle positive integers:

'0'.repeat( Math.max(4 - num.toString().length, 0)) + num

Create a string by repeat adding zeros, as long as the number of digits (length of string) is less than 4 Add the number, that is then converted to a string also.

Edit: from now on you should probably use this function:

String(num).padStart(4,'0')

It still doesn't handle negative numbers...

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.

I don't think there's anything "built" into the JavaScript language for doing this. Here's a simple function that does this:

function FormatNumberLength(num, length) {
    var r = "" + num;
    while (r.length < length) {
        r = "0" + r;
    }
    return r;
}


FormatNumberLength(10000, 5) outputs '10000'
FormatNumberLength(1000, 5)  outputs '01000'
FormatNumberLength(100, 5)   outputs '00100'
FormatNumberLength(10, 5)    outputs '00010'

This might help :

String.prototype.padLeft = function (length, character) { 
     return new Array(length - this.length + 1).join(character || '0') + this; 
}

var num = '12';

alert(num.padLeft(4, '0'));

2023

Internationalization API's number format can do even this:

const digits3 = 
    new Intl.NumberFormat(
        undefined, 
        { minimumIntegerDigits: 3, maximumSignificantDigits: 3 });

digits3.format(42);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat

A funny (but interesting) way to prefix numbers with zeros:

function FormatInteger(num, length) {

    return (num / Math.pow(10, length)).toFixed(length).substr(2);
}

How about something like this:

function prefixZeros(number, maxDigits) 
{  
    var length = maxDigits - number.toString().length;
    if(length <= 0)
        return number;

    var leadingZeros = new Array(length + 1);
    return leadingZeros.join('0') + number.toString();
}
//Call it like prefixZeros(100, 5); //Alerts 00100

I think the most compact yet intuitive way is:

function toFixedLength(input, length, padding) {
    padding = String(padding || "0");
    return (padding.repeat(length) + input).slice(-length);
}

The slice method here could be replaced with substr if that is more intuitive to the coder.

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

Latest with ES6 repeat() method:

    const length_required = 5;
    let num = 10;
    num = "0".repeat(length_required - String(num).length) + num;
    console.log(num)
    // output: 00010

    let num = 1000;
    num = "0".repeat(length_required - String(num).length) + num;
    console.log(num)
    // output: 01000

You could go crazy with methods like these:

function PadDigits(input, totalDigits) 
{ 
    var result = input;
    if (totalDigits > input.length) 
    { 
        for (i=0; i < (totalDigits - input.length); i++) 
        { 
            result = '0' + result; 
        } 
    } 
    return result;
} 

But it won't make life easier. C# has a method like PadLeft and PadRight in the String class, unfortunately Javascript doesn't have this functionality build-in

I ran into much the same problem and I found a compact way to solve it. If I had to use it multiple times in my code or if I was doing it for any more than four digits, I'd use one of the other suggested solutions, but this way lets me put it all in an expression:

((x<10)?"000": (x<100)?"00": (x<1000)?"0": "") + x

It's actually the same as your code, but using the ternary operator instead of "if-else" statements (and moving the "+ x", which will always be part of the expression, outside of the conditional code).

Another one:

function format_number_length(num, length) {
    var r = num.toString();
    if (r.length<length) r = Array(length - r.length + 1).join('0') + r;
    return r;
}

In JavaScript we have string method padStart.

This is example from https://www.w3schools.com/js/js_string_methods.asp

let numb = 5;
let text = numb.toString();
let padded = text.padStart(4, "0");

A "while" loop should make this easy enough.

function formatLength(a) {
    var num = document.getElementById(a)
    while (num.value.length < 4) {
        num.value = '0' + num.value
    }
}

That would loop through until the length of the num value reached 4 digits (assuming you have passed in the id of the number element as an argument)

I know this question is kind of old, but for anyone looking for something similar to String formatting on Java or Python, I have these helper methods:

String.format = (...args) => {
    if( args.length == 0 ){
        throw new Error("String format error: You must provide at least one argument");
    }
    const delimiter = "@LIMIT*";
    const format = String(args.shift(1,0)).replace(/(%[0-9]{0,}[sd])/g, delimiter+"$1"+delimiter).split(delimiter); // First element is the format
    if( [...format].filter(el=>el.indexOf("%")>-1).length != args.length ){
        throw new Error("String format error: Arguments must match pattern");
    }
    if( format.length == 1 && args.length == 0 ){
        return String(format);
    }
    let formattedString = "";
    // patterns
    const decimalPattern = /%[0-9]{0,}d/;
    const stringPattern  = /%s/;
    if( format.length == 0 ){
        throw new Error("String format error: Invalid format");
    }
    let value        = null;
    let indexOfParam = 0;
    let currPattern  = null;
    while( args.length > 0 ) {
        currPattern = format[indexOfParam];
        indexOfParam++;
        if( currPattern.indexOf("%")<0 ){
            formattedString+=currPattern;
            continue;
        }
        value = args.shift(0,1);
        if( decimalPattern.test(currPattern) ){
            let numberLength = parseInt(currPattern.replace(/[^0-9]/g,''));
            if( isNaN(numberLength) ){
                numberLength = 0;
            }
            formattedString+=numberToLength(value, numberLength);
        } else if( stringPattern.test(currPattern) ) {
            if( typeof value === 'object' && value.toSource ){
                formattedString+=String(value.toSource());
            } else {
                formattedString+=String(value);
            }
        } else {
            throw new Error("String format error: Unrecognized pattern:"+currPattern);
        }
    }
    return formattedString;
}

const numberToLength = (number, length) => {
    length = parseInt(length);
    number = String(number);
    if( isNaN(length) || isNaN(parseInt(number)) ){
        throw new Error("Invalid number passed");
    }
    while( number.length < length ) {
        number = "0" + number;
    }
    return number;
}

本文标签: formattingHow can I format an integer to a specific length in javascriptStack Overflow