Javascript adding zeros to the beginning of a string (max length 4 chars)

后端 未结 11 860
轻奢々
轻奢々 2020-12-10 23:58
var number = 1310;

should be left alone.

var number = 120;

should be changed to \"0120\";

var num         


        
11条回答
  •  一整个雨季
    2020-12-11 00:33

    Nate as the best way I found, it's just way too long to read. So I provide you with 3 simples solutions.

    1. So here's my simplification of Nate's answer.

    //number = 42
    "0000".substring(number.toString().length, 4) + number;
    

    2. Here's a solution that make it more reusable by using a function that takes the number and the desired length in parameters.

    function pad_with_zeroes(number, len) {
      var zeroes = "0".repeat(len);
      return zeroes.substring(number.toString().length, len) + number;
    }
    
    // Usage: pad_with_zeroes(42,4);
    // Returns "0042"
    

    3. Here's a third solution, extending the Number prototype.

    Number.prototype.toStringMinLen = function(len) {
      var zeroes = "0".repeat(len);
      return zeroes.substring(self.toString().length, len) + self;
    }
    
    //Usage: tmp=42; tmp.toStringMinLen(4)
    

提交回复
热议问题