Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to alphabet string (Javascript)

I want to convert a number to a char like:

  • if number = 1 then A
  • if number = 26 then Z
  • if number = 27 then AA
  • if number = 676 then ZZ
  • if number = 456976 then ZZZZ

Tried to find anything to help me with but I did not had any lucky. Anybody have a sample for this using JavaScript?

Thank you!

like image 609
Ricardo Andrade Avatar asked Aug 20 '17 22:08

Ricardo Andrade


People also ask

How do you convert numbers into alphabets?

The Letter-to-Number Cipher (or Number-to-Letter Cipher or numbered alphabet) consists in replacing each letter by its position in the alphabet , for example A=1, B=2, Z=26, hence its over name A1Z26 .

How do you convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.


1 Answers

The number conversion you've shown doesn't seem consistent. It seems you want to convert a number to the equivalent spreadsheet column letter, similar to this Python question: Convert spreadsheet number to column letter.

Converting that code to javascript (and cleaning up a bit) gives:

function numToSSColumn(num){
  var s = '', t;

  while (num > 0) {
    t = (num - 1) % 26;
    s = String.fromCharCode(65 + t) + s;
    num = (num - t)/26 | 0;
  }
  return s || undefined;
}


// A  Z AA  CZ  DA  YZ  ZZ AAA
[0,1,26,27,104,105,676,702,703,
//AAZ ABA  AZZ  BAA  BAZ  BBA   YYYZ   ZZZZ
  728,729,1378,1379,1404,1405,456976,475254].forEach(function(n) {
  console.log(n + ' : ' + numToSSColumn(n));
});

The function doesn't check the input and returns undefined if n < 0.

Your conversions don't seem to work because spreadsheet columns don't start from 0, they start from 1, so A-Z is 1 to 26, AA to AZ is 27 to 52, and so on. 676 is YZ and 456976 is YYYZ. ZZZZ is 475254 (or 11110 base26);

like image 133
RobG Avatar answered Sep 19 '22 21:09

RobG