Following yesterday’s post, I thought it appropriate to write a quick JavaScript function which converts an integer into the corresponding column name:


/**
 * Takes a positive integer and returns the corresponding column name.
 * @param {number} num  The positive integer to convert to a column name.
 * @return {string}  The column name.
 */
function toColumnName(num) {
  for (var ret = '', a = 1, b = 26; (num -= a) >= 0; a = b, b *= 26) {
    ret = String.fromCharCode(parseInt((num % b) / a) + 65) + ret;
  }
  return ret;
}

You can click here to enter a positive integer and see the corresponding column name. If you need this function for a project, feel free to use it as long as you give credit. 😎


6 Comments

Ricardo Visbal · September 21, 2016 at 2:26 PM

Very cool function 🙂

    V · July 4, 2018 at 9:57 AM

    Except it’s impenetrable and completely devoid of documentation (but “wheyhey!” it’s only on five lines, that’ll really help the poor soul who has to maintain your code).

DinEsh · October 17, 2016 at 7:39 AM

Hi chris.

can i get full program of This convert excel column to alphabets ?

function toColumnName(num) {
for (var ret = ”, a = 1, b = 26; (num -= a) >= 0; a = b, b *= 26) {
ret = String.fromCharCode(parseInt((num % b) / a) + 65) + ret;
}
return ret;
} i need to understand this in html program.

Haris · June 17, 2017 at 3:10 AM

Great Job…

Charles · October 25, 2017 at 11:59 AM

Thanks. Fixed a nagging issue with this

Fajarullah · February 6, 2019 at 1:53 AM

thanks

Leave a Reply to DinEsh Cancel reply

Your email address will not be published. Required fields are marked *