14
\$\begingroup\$

I want to implement numbering scheme like Microsoft Word uses for numbering. first one gets = A,next is B, next is C, .... then AA, then AB,....and so on. as shown below

 A 
 B
 C
 . 
 .
 AA
 AB
 AC
 .
 .
 AAA
 AAB
 ....

'=>' here means converted to.

some examples:

1 => A
26 => Z
27 => AA
52 => AZ
53 => BA

and heres the code for it:

 var convertToNumberingScheme = function(n){
 var x = n-1,
 r26 = x.toString(26),
 baseCharCode = "A".charCodeAt(0);
 var arr = r26.split(''),
 len = arr.length;
 var newArr =arr.map(function(val,i){
 val = parseInt(val,26);
 if( (i === 0) && ( len > 1)){
 val = val-1;
 }
 return String.fromCharCode(baseCharCode + val);
 });
 return newArr.join('');
 }

It seems to work fine, but any ideas if there are some potential bugs or ways to optimize this.

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Oct 2, 2012 at 21:16
\$\endgroup\$
2
  • 1
    \$\begingroup\$ If you're using HTML then just place ul or ol. \$\endgroup\$ Commented Oct 2, 2012 at 21:30
  • \$\begingroup\$ @LarryBattle Thanks. But it is a custom canvas app, can't use ul,li but good pointer nonetheless . \$\endgroup\$ Commented Oct 2, 2012 at 21:34

1 Answer 1

16
\$\begingroup\$

The function in the question converts to base 26, then splits the resulting string, and converts each digit back to decimal - and then to a letter. That seems roundabout.

Here's a simpler one:

function convertToNumberingScheme(number) {
 var baseChar = ("A").charCodeAt(0),
 letters = "";
 do {
 number -= 1;
 letters = String.fromCharCode(baseChar + (number % 26)) + letters;
 number = (number / 26) >> 0; // quick `floor`
 } while(number > 0);
 return letters;
}

This function basically does a repeated "divmod" of the input number; getting the modulus 26 and the quotient (floor of n divided by 26). The modulus is converted to a A-Z character that's prepended to the output string, and the quotient is used as the input for the next iteration of the loop.

answered Oct 2, 2012 at 22:26
\$\endgroup\$
1
  • \$\begingroup\$ This is very helpful, specifically in converting the number to a letter codepoint. I used this in combination with exceljs to good effect, thanks. \$\endgroup\$ Commented Dec 7, 2021 at 3:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.