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

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

    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;
    }
    
    0 讨论(0)
  • 2021-02-03 17:38

    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'));
    
    0 讨论(0)
  • 2021-02-03 17:40

    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.

    0 讨论(0)
  • 2021-02-03 17:47

    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

    0 讨论(0)
  • 2021-02-03 17:47

    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;
    }
    
    0 讨论(0)
  • 2021-02-03 17:48

    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
    
    0 讨论(0)
提交回复
热议问题