Para a conversão de dados primitivos, vamos utilizar as funções mostradas na sintaxe abaixo:
Sintaxe
func FormatInt(i int64, base int) string
func FormatFloat(f float64, fmt byte, prec, bitSize int) string
func FormatBool(x bool) string
func Itoa(i int) string
func Atoi(s string) (int, error)
func ParseInt(s string, base int, bitSize int) (i int64, err error)
func ParseFloat(s string, bitSize int) (float64, error)
func ParseBool(str string) (bool, error)
Onde
i,f,x,s: valores que desejamos converter
base: base numérica 2, 10, 16. São aceitas bases até 36.
fmt: formato:
'b': -ddddp±ddd
'e':-d.dddde±dd
'f': -ddd.dddd
'x':-0xd.ddddp±ddd
prec: número de casas decimais
bitSize: tamanho do dado em bits: 8, 16, 32 e 64
Exemplo 1
package main
import (
"fmt"
"strconv"
)
func main() {
a := strconv.Itoa(12)
fmt.Printf("%q\n", a)
// string -> inteiro
b, _ := strconv.Atoi("12")
fmt.Printf("%d\n", b)
// string -> bool
c, _ := strconv.ParseBool("true")
fmt.Printf("%t\n", c)
// string -> float
d, _ := strconv.ParseFloat("9.99", 32) //32 bits
fmt.Printf("%0.2f\n", d)
// string -> int
e, _ := strconv.ParseInt("100", 10, 32) //base 10, 32bits
fmt.Printf("%d\n", e)
// string -> int
f := strconv.FormatInt(-1, 10)
fmt.Printf("%q\n", f)
g := strconv.FormatFloat(9.99, 'f', 2, 32)
fmt.Printf("%q\n", g)
h := strconv.FormatBool(false)
fmt.Printf("%q\n", h)
}
Saída
"12"
12
true
9.99
100
"-1"
"9.99"
"false"