Converting between strings and numeric types in Golang

Converting String to Numeric Types

In actual development, we often need to convert some commonly used data types. Proficiency allows us to write programs with less effort.

Conversion between string and int types

This should be the easiest type conversion to encounter in normal development.

Choke ():int->string

Itoa() function is used to convert int type data to the corresponding string type

package main
 import  ( 
	"fmt" 
	"strconv" 
) 
func  main ( )  {  /*{ cannot be on a single line*/ 
	num :=  69 
	str := strconv .Itoa ( num ) 
	fmt . Println ( str ) 
	fmt . Printf ( " str type:%T\n" , str ) }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

output:

69

str type:string

Atoi ():string->int

The Atoi() function is used to convert an integer of type string to type int.

Function prototype:func Atoi(s string) (i int, err error)

  • It can be seen from the function signature that the Atoi() function has two return values, i is the integer type that has been successfully converted, and err is the corresponding error message when the conversion is successful and the conversion fails.
package main
 import  ( 
	"fmt" 
	"strconv" 
) 
func  main ( )  {  /*{ cannot be on a single line*/ 
	str1 :=  "69" 
	str2 :=  "i69" 
	num1 , err := strconv . Atoi ( str1 ) 
	if err !=  nil { 
		fmt . Println ( "Conversion failed!" , str1 ) 
	} else { 
		fmt . Printf ( "Conversion succeeded! value:%d type:%T\n", num1 , num1 ) 
	} 
	num2 , err := strconv . Atoi ( str2 ) 
	if err !=  nil { 
		fmt . Println ( "Conversion failed!" , str2 ) 
	} else { 
		fmt . Printf ( "Conversion succeeded! value:%d type:%T\n" , num2 , num2 ) 
	} 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

output:

Conversion successful! value:69 type:int
conversion failed! i6a

Parse series

ParseBool (): string->bool

The ParseBool() function is used to convert a string to a value of type bool, it can only accept 1, 0, t, f, T, F, true, false, True, False, TRUE, FALSE, other values ​​return an error .

package main
 import  ( 
	"fmt" 
	"strconv" 
) 
func  main ( )  {  /*{ cannot be on a single line*/ 
	str1 =  "2" 
	str2 =  "t" 
	bool1 , err := strconv . ParseBool ( str1 ) 
	if err !=  nil { 
		fmt . Println ( "Conversion failed!" , str1 ) 
	} else { 
		fmt . Printf ( "Conversion succeeded! value:%v type:%T\n", bool1 , bool1 ) 
	} 
	bool2 , err := strconv . ParseBool ( str2 ) 
	if err !=  nil { 
		fmt . Println ( "Conversion failed!" , str2 ) 
	} else { 
		fmt . Printf ( "Conversion succeeded! value:%v type:%T\n" , bool2 , bool2 ) 
	} 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

output:

Conversion failed! 2
Conversion successful! value:true type:bool

ParseInt(): string->int

The ParseInt() function is used to return an integer value represented by a string (can contain a sign)

Function prototype:func ParseInt(s string, base int, bitSize int) (i int64, err error)

  • base specifies the base, the value range is 2 to 36. If base is 0, it will be judged from the front of the string, "0x" is hexadecimal, "0" is octal
  • bitSize specifies the integer type that the result must be able to assign without overflow, 0, 8, 16, 32, 64 represent int, int8, int16, int32, int64 respectively
package main

import (
	"fmt"
	"strconv"
)

func  main ( )  {  /*{ cannot be on a single line*/ 
	str1 :=  "-69" 
	str2 :=  "18461890471234" 
	num1 , err := strconv . ParseInt ( str1 , 10 , 32 ) 
	if err !=  nil { 
		fmt . Println ( err ) 
	} else { 
		fmt . Printf ( "value:%d type:%T\n" , num1 , num1 ) 
	}
	num2,err := strconv.ParseInt(str2,10,32)
	if err != nil{
		fmt.Println(err)
	}else{
		fmt.Printf("value:%d type:%T\n",num2,num2)
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

output:

value:-69 type:int64
strconv.ParseInt: parsing “18461890471234”: value out of range

Note: ParseUnit() is similar to the ParseInt() function, except that it does not accept signs

ParseFloat(): string->float

The ParseFloat() function is used to return a floating point number represented by a string

Function prototype:func ParseFloat(s string, bitSize int) (f float64, err error)

  • If s is grammatical, the function returns a floating-point number closest to the value represented by s (rounded using the IEEE754 specification).
  • bitSize specifies the type of the return value, 32 means float32, 64 means float64;
package main

import (
	"fmt"
	"strconv"
)

func  main ( )  {  /*{ cannot be on a single line */ 
	str2 :=  "1846.34" 
	num2 , err := strconv . ParseFloat ( str2 , 64 ) 
	if err !=  nil { 
		fmt . Println ( err ) 
	} else { 
		fmt . Printf ( "value:%f type:%T\n" , num2 , num2 ) 
	} 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

output:

value:1846.340000 type:float64

Format series

FormatBool(): bool -> string

The FormatBool() function can convert a bool type value to the corresponding string type

package main

import (
   "fmt"
   "strconv"
)

func  main ( )  {  /*{ cannot be on a single line */ 
   bool1 :=  false 
   str1 := strconv . FormatBool ( bool1 ) 
   fmt . Printf ( "value:%s type:%T" , str1 , str1 ) 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

output:

value:false type:string

FormatInt(): int -> string

The FormatInt() function is used to convert integer data to the specified base and return it as a string

Function prototype:func FormatInt(i int64, base int) string

  • The parameter i must be of type int64
  • The parameter base, base hexadecimal, must be between 2 and 36, and lowercase letters "a" to "z" will be used in the returned result to represent numbers greater than 10.
package main

import (
	"fmt"
	"strconv"
)

func  main ( )  {  /*{ cannot be on a single line*/ 
	var num1 int64  =  100 
	str1 := strconv . FormatInt ( num1 , 8 ) 
	fmt . Printf ( "value:%s type:%T\n" , str1 , str1 ) 
	str1 = strconv . FormatInt ( num1 , 16 ) 
	fmt . Printf ( "value:%s type:%T\n" , str1 , str1) 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Note: The FormatUint() function is similar to the FormatInt() function, but the parameter i must be an unsigned uint64 type, and the function signature is as follows.func FormatUint(i uint64, base int) string

FormatFloat(): float -> string

The FormatFloat() function is used to convert floating point numbers to string type.

Function prototype:func FormatFloat(f float64, fmt byte, prec, bitSize int) string

  • bitSize indicates the source type of the parameter f (32 for float32, 64 for float64), and will be rounded accordingly.
  • fmt indicates the format, which can be set to "f" for -ddd.dddd, "b" for -ddddp±ddd, and the exponent is binary, "e" for -d.dddde±dd decimal exponent, "E" for -d.ddddE ±dd decimal exponent, "g" means use "e" format when the exponent is very large, otherwise "f" format, "G" means use "E" format when the exponent is very large, otherwise "f" format.
  • prec controls the precision (excluding the exponent part): when the parameter fmt is "f", "e", "E", it indicates the number of digits after the decimal point; when the parameter fmt is "g", "G", it controls total number of digits. If prec is -1, it means that f is represented by the minimum but required number of digits.
package main

import (
	"fmt"
	"strconv"
)

func  main ( )  {  /*{ cannot be on a single line */ 
	var num1 float64  =  324.2148 
	str1 := strconv . FormatFloat ( num1 , 'f' , 4 , 64 ) 
	fmt . Printf ( "value:%s type:%T\ n" , str1 , str1 ) 
	str1 = strconv . FormatFloat ( num1 , 'e' , 5 , 64 ) 
	fmt .Printf("value:%s type:%T\n",str1,str1)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

output:

value:324.2148 type:string
value:3.24215e+02 type:string

Append series

Append series functions are used to convert the specified type into a string and append it to a slice. It includes AppendBool(), AppendFloat(), AppendInt(), AppendUint().

package main
 import  ( 
	"fmt" 
	"strconv" 
) 
func  main ( )  {  /*{ cannot be on a single line*/ 
	Slice :=  [ ] byte ( "int (base 10): " ) 
	Slice = strconv . AppendInt ( Slice , 100 , 10 ) 
	fmt . Println ( string ( Slice ) ) 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

output:

int (base 10):100

Related: Converting between strings and numeric types in Golang