Count golang number size

3

I have a variable int , I need to know how many houses it has and capture the number for each house, for example my number is 57890 , I need to return the house quantity of that number, 57890 = 5 . I also need the number that is present in each position position 3 = 8 .

    
asked by anonymous 27.05.2017 / 13:27

2 answers

4

The easiest way is to convert with Itoa() to text and get the characters with len() . But you can also do mathematically (module math ).

package main
import ("fmt"
        "strconv"
        "math")

func main() {
    t := strconv.Itoa(57890)
    fmt.Println("Tamanho matematicamente calculado:", math.Floor(math.Log10(math.Abs((57890)))) + 1)
    for i := 0; i < len(t); i++ {
        fmt.Printf("%c\n", t[i])
    }
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

I got element 2 because the index starts at 0, so the third is number 2.

Note that conversions are not necessary as there will be only ASCII characters.

    
27.05.2017 / 14:09
2

For the first case, use the strconv method. Itoa() " to convert the numeric value to string and method len() to check the file size. For the second situation, use rune(str)[position] in which, position represents the position of the string passed as parameter. Remember that you said 3 position, however since the vector starts with 0 , the return relative to the 3 position would be 9 . See:

package main
import ("fmt"
        "strconv")

func main() {
    str := strconv.Itoa(57890)
    fmt.Println(len(str))

    // index inicia com 0. então 2 representa a posição 3
    fmt.Println(string([]rune(str)[0])) // saida 5
    fmt.Println(string([]rune(str)[1])) // saida 7
    fmt.Println(string([]rune(str)[2])) // saida 8
}

See funfando no play golang .

    
27.05.2017 / 14:36