# number to characters function

This is a short snippet for converting number to characters in alphabet. For example, 3 should be D, 7 is H. It should be a problem when trying to convert a number bigger than 25 (length of alphabet is 26, I am counting from 0). It that case, we got more than one character – for example 26 is AA, 150 is FU, 2222 is DHM.

This code should be used for example for converting number of column to its name in Excel.

Code in coffeescript:

1 2 3 4 5 6 7 8 9 10 11 12 |
numberToChar = (val) -> rest = val charString = '' # output string a = 26 # number of chars in alphabet noOfChars = Math.ceil Math.log(val+2) / Math.log(a) #number of characters in output for i in [noOfChars..1] f = Math.floor(val/(Math.pow a,i-1)) charString += String.fromCharCode 65 + f%a rest -= f*a charString |

In javascript:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function numberToChar (val) { var rest = val; var charString = ''; // output string var a = 26; // number of chars in alphabet var noOfChars = Math.ceil(Math.log(val+2)/ Math.log(a)); //number of characters in output for (var i = noOfChars; i!= 0; i--){ var f = Math.floor(val/(Math.pow(a,i-1))); charString += String.fromCharCode(65 + f%a); rest -= f*a; } return charString } |

In action:

See the Pen coffeescript function for converting number to string of characters by Eidam (@eidam61) on CodePen.