跪拜 Guibai
← Back to the summary

Go Type Conversion: When Truncation, Not Rounding, Strips Your Decimals

Type Conversion

In real-world development, different types often need to be converted into each other: string to number, number to string, float to integer, integer to float, and so on.

Number Conversion

Suppose you have a float 3.1415926535 and want to turn it into an integer. You can use int() to convert it:

package main
import "fmt"

func main() {
	num := 3.1415926535
	intNum := int(num)
	fmt.Println(intNum) // 3
}

As you can see, int() converts a float to an integer by simply discarding the decimal part (no rounding).

Other numeric type conversions are written similarly and are easy to remember — the names are exactly the same as when defining the types:

Number to String

Converting between numbers and strings requires the strconv (string convert) package. For example, converting the integer 3 to a string:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	num := 3
	strNum := strconv.Itoa(num)
	fmt.Printf("type: %T, value: %v", strNum, strNum)
	// type: string, value: 3
}

A few notes:

  1. When importing multiple packages, group them with (), one package per line.
  2. strconv.Itoa() stands for Int to ASCII: it converts an integer to a string (a string is essentially a sequence of characters).
  3. In fmt.Printf(), %T prints the type and %v prints the value.

String to Number

Conversely, converting a string to a number is also common. In Go, strings and numbers cannot be operated on directly; they must first be converted to the same type. For example, this will error:

var a = "10"
var b = 20
var c = a + b // error: string and number cannot be operated on directly

In this case, you can use strconv.Atoi() to convert the string to an integer:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "10"
	num, _ := strconv.Atoi(str)
	fmt.Printf("type: %T, value: %v", num, num)
	// type: int, value: 10
}

Atoi is short for ASCII to Int. It returns two values: the conversion result and an error. When conversion fails, the second return value is not nil; here _ is used to ignore the error, indicating that failure cases are not handled for now.

String to Boolean

Use strconv.ParseBool() to convert a string to a boolean. It also returns two values: result + error:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "true"
	b, _ := strconv.ParseBool(str)
	fmt.Printf("type: %T, value: %v", b, b)
	// type: bool, value: true
}

ParseBool recognizes the following truthy values: 1, t, T, TRUE, true, True; and falsy values: 0, f, F, FALSE, false, False. Any other string will cause the conversion to fail.

Boolean to String

Conversely, use strconv.FormatBool() to convert a boolean to a string. The result will only be "true" or "false":

package main

import (
	"fmt"
	"strconv"
)

func main() {
	flag := true
	str := strconv.FormatBool(flag)
	fmt.Printf("type: %T, value: %v", str, str)
	// type: string, value: true
}

Exercises

  1. Numeric conversion: Declare a float64 variable with the value 9.99, convert it to an integer using int() and print it; then convert the result back using float64() and observe whether the decimal part is still there.
  2. Number to string: Declare an int variable representing age, convert it to a string using strconv.Itoa(), and print the type and value with fmt.Printf (confirm the type is string).
  3. String to number: Declare two strings "15" and "27", convert each to an integer using strconv.Atoi(), add them together, and print the sum.
  4. Boolean conversion: Pass the strings "1", "false", and "yes" to strconv.ParseBool() respectively, and print the result and error of each conversion (this time do not use _ to ignore the error; see which ones succeed).
  5. Combined exercise: Declare a string price "199.5" and a discount flag "true". First convert the price to float64 using strconv.ParseFloat(str, 64), and the discount flag to a boolean using ParseBool; if the discount applies, take 20% off, then finally convert the amount payable to a string using strconv.FormatFloat and print it.