Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang Alphabetic representation of a number

Is there an easy way to convert a number to a letter?

For example,
3 => "C" and 23 => "W"?

like image 387
Pete Avatar asked Apr 22 '16 22:04

Pete


1 Answers

If you need not a rune, but a string and also more than one character for e.g. excel column

package main

import (
    "fmt"
)

func IntToLetters(number int32) (letters string){
    number--
    if firstLetter := number/26; firstLetter >0{
        letters += IntToLetters(firstLetter)
        letters += string('A' + number%26)
    } else {
        letters += string('A' + number)
    }
        
    return 
}

func main() {
    fmt.Println(IntToLetters(1))// print A
    fmt.Println(IntToLetters(26))// print Z
    fmt.Println(IntToLetters(27))// print AA
    fmt.Println(IntToLetters(1999))// print BXW
}

preview here: https://play.golang.org/p/GAWebM_QCKi

I made also package with this: https://github.com/arturwwl/gointtoletters

like image 101
arturwwl Avatar answered Sep 28 '22 12:09

arturwwl