Convert numbers to letters beyond the 26 character alphabet

后端 未结 3 772
故里飘歌
故里飘歌 2020-11-27 19:28

I\'m creating some client side functions for a mappable spreadsheet export feature.

I\'m using jQuery to manage the sort order of the columns, but each column is ord

相关标签:
3条回答
  • 2020-11-27 20:06

    You can use code like this, assuming that numbers contains the numbers of your columns. So after this code you'll get the string names for your columns:

    var letters = ['a', 'b', 'c', ..., 'z'];
    var numbers = [1, 2, 3, ...];
    var columnNames = [];
    for(var i=0;i<numbers.length;i++) {
        var firstLetter = parseInt(i/letters.length) == 0 ? '' : letters[parseInt(i/letters.length)];
        var secondLetter = letters[i%letters.length-1];
        columnNames.push(firstLetter + secondLetter);
    }
    
    0 讨论(0)
  • 2020-11-27 20:12

    This is a very easy way:

    function numberToLetters(num) {
        let letters = ''
        while (num >= 0) {
            letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[num % 26] + letters
            num = Math.floor(num / 26) - 1
        }
        return letters
    }
    
    0 讨论(0)
  • 2020-11-27 20:16

    I think you're looking for something like this

        function colName(n) {
            var ordA = 'a'.charCodeAt(0);
            var ordZ = 'z'.charCodeAt(0);
            var len = ordZ - ordA + 1;
          
            var s = "";
            while(n >= 0) {
                s = String.fromCharCode(n % len + ordA) + s;
                n = Math.floor(n / len) - 1;
            }
            return s;
        }
    
    // Example:
    
        for(n = 0; n < 125; n++)
                document.write(n + ":" + colName(n) + "<br>");

    0 讨论(0)
提交回复
热议问题