Reputation: 1270
My question is how do I get the corresponding letter(s) from a number.
So
0 => 0 // 0 stays 0
1 => A
2 => B
3 => C
26 => Z
27 => AA
28 => AB
55 => AC
702 => ZZ
The number will definitely not be over 702.
Is there some kind of method I can use to do this?
Upvotes: 1
Views: 193
Reputation: 18619
Split the number into parts by doing a modulo by 26
, then use String.fromCharCode
to convert it to a character:
function numToExcelColumnName(n){
if(!n) return 0
n-- //Make 0 => A
const lower = n % 26
const upper = Math.floor(n / 26)
return (
upper
? String.fromCharCode(65 + upper - 1)
: ''
)
+ String.fromCharCode(65 + lower)
}
You can even extend this code to handle numbers above 702 as well by adding a loop:
function numToExcelColumnName(n){
if(!n) return 0
let output = ''
while(n){
n--
output = String.fromCharCode(65 + n % 26) + output
n = Math.floor(n / 26)
}
return output
}
Upvotes: 2
Reputation: 2804
I liked the challenge, so I wrote the following code:
function NumbersToLetters(num) {
var letArr=[];
function numToLet(letterArray, number) {
if(number>0) {
var whole=Math.floor((number-1)/26);
var reminder=(number-1)%26;
letterArray.unshift(String.fromCharCode(65+reminder));
numToLet(letterArray, whole);
}
};
numToLetters(letArr, num);
return letArr.length?letArr.join(""):"0";
}
To be used:
NumbersToLetters(num);
Upvotes: 0
Reputation:
For single characters like A,B... you can get the number easily by
num = ord(x)-65
where x is the corresponding character (A,B...)
For Double letters like (AB,BG,..)
num = ord(str[0]-65)*26+(str[1]-65)
where str = xy where x and y are corresponding characters
Upvotes: 0