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:
int(): convert tointint8(): convert toint8int16(): convert toint16int32(): convert toint32int64(): convert toint64uint(): convert touintuint8(): convert touint8uint16(): convert touint16uint32(): convert touint32uint64(): convert touint64float32(): convert tofloat32float64(): convert tofloat64
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:
- When importing multiple packages, group them with
(), one package per line. strconv.Itoa()stands for Int to ASCII: it converts an integer to a string (a string is essentially a sequence of characters).- In
fmt.Printf(),%Tprints the type and%vprints 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
- Numeric conversion: Declare a
float64variable with the value9.99, convert it to an integer usingint()and print it; then convert the result back usingfloat64()and observe whether the decimal part is still there. - Number to string: Declare an
intvariable representing age, convert it to a string usingstrconv.Itoa(), and print the type and value withfmt.Printf(confirm the type isstring). - String to number: Declare two strings
"15"and"27", convert each to an integer usingstrconv.Atoi(), add them together, and print the sum. - Boolean conversion: Pass the strings
"1","false", and"yes"tostrconv.ParseBool()respectively, and print the result and error of each conversion (this time do not use_to ignore the error; see which ones succeed). - Combined exercise: Declare a string price
"199.5"and a discount flag"true". First convert the price tofloat64usingstrconv.ParseFloat(str, 64), and the discount flag to a boolean usingParseBool; if the discount applies, take 20% off, then finally convert the amount payable to a string usingstrconv.FormatFloatand print it.