Convert an integer to a base26 alpha string

24. February 2011 15:18

In case you ever need to convert an integer to an alpha (such as the top of a spreadsheet). A-Z, AA-AZ etc.

function intToAlpha26String(input) {
    input = (+input).toString(26);
    var ret = [];
    while (input.length) {
        var a = input.charCodeAt(input.length-1);
        if (input.length > 1)
            input = (parseInt(input.substr(0, input.length - 1), 26) - 1).toString(26);
        else
            input = "";

        if (a >= 48/*'0'*/ && a <= 57 /*'9'*/)
            ret.unshift(String.fromCharCode(a + 49)); //raise to += 'a'
        else
            ret.unshift(String.fromCharCode(a + 10)); //raise + 10 (make room for 0-9)
    }
    return ret.join('').toUpperCase();
}
Hope this helps, let me know if you need the reverse, may just work that one out. Nice that JS supports some fairly broad base classifications that other languages don't. This actually translates fairly nicely into actionscript.
T-SQL
CREATE FUNCTION [dbo].[IntToBase26Alpha]
(
	@input AS int
)
RETURNS varchar(MAX)
AS
BEGIN
	DECLARE @ret AS varchar(MAX)	
	DECLARE @debug as VARCHAR(MAX);
	
	DECLARE @process AS int
	DECLARE @current AS int
	
	SET @ret = ''
	SET @process = CASE WHEN (@input is null or @input < 1) THEN 0 ELSE @input END
	SET @debug = ''
	
	WHILE (@process >= 0)
	BEGIN

		SET @current = @process % 26
		SET @process = ROUND(@process / 26, 0) - 1
		SET @ret = CHAR(@current + 65) + @ret

	END
	
	Return @ret
END
GO

Tags:

Comments are closed

Tracker1

Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.